WebSocket protocol and packet capture

WebSocket protocol

WebSocket is not a new agreement, but to use the HTTP protocol to establish a connection, it aims to establish a two-way communication channel unrestricted between the browser and the server, for example, you can send a message to the server at any time browser


WebSocket connection must be initiated by the browser, because the request is a standard HTTP protocol requests, the following format:

GET ws://localhost:3000/ws/chat HTTP/1.1
Host: localhost
Upgrade: websocket
Connection: Upgrade
Origin: http://localhost:3000
Sec-WebSocket-Key: client-random-string
Sec-WebSocket-Version: 13

The request and the regular HTTP There are several differences:

  1. GET request address is not similar to the / path /, but in ws: // at the beginning of the address;
  2. Request header Upgrade: websocket and Connection: Upgrade indicates that the connection is to be converted to WebSocket connection;
  3. Sec-WebSocket-Key is used to identify the connection, it is not used to encrypt the data;
  4. Sec-WebSocket-Version specifies the WebSocket protocol version

Subsequently, if the server accepts the request, it returns the following responses:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: server-random-string

The response code 101indicates the current HTTP protocol connection is going to be changed, the changed protocol is Upgrade: websocketspecified WebSocket protocol.

The version number and the sub-agreement parties can understand the data formats, and supports compression and so on. If only the WebSocket API, you do not need to care about these


Relations HTTP protocol, WebSocket protocol and TCP protocol

      HTTP protocol is built on top of TCP protocol, TCP protocol itself to achieve a full-duplex communication, but the HTTP protocol request - response mechanism to limit the full-duplex communication. After the WebSocket connection is established, in fact, it simply provides: Next, we can not communicate using the HTTP protocol, the data is sent directly to each other now.

      Secure WebSocket connection mechanism and HTTPS similar. First, the browser with wss: // xxx When you create a WebSocket connection, will create a secure connection through HTTPS, then HTTPS connection upgraded to the WebSocket connection, taking the underlying communication is still secure SSL / TLS protocol 


 

fiddler crawl WebSocket data

fiddlerDouble-click WebSocket Sessionto view the data connection and received

 

Guess you like

Origin www.cnblogs.com/SitVen/p/11665064.html