Understand the basic principle of WebSocket with Rongyun WebSDK
Recently, I used Rongyun to develop chat pages. Through packet capture, I found that The SDK of Rongyun uses WebSocket to communicate with the server, so I have a simple understanding of the implementation principle of WebSocket
Rongyun SDK documentation: docs.rongcloud.cn/v4/
WebSocket to HTTP
1. The HTTP protocol has not changed for WebSocket
2. WebSocket is a new protocol after HTTP
The two have intersection, but also different
4. WebSocket uses HTTP protocol to complete part of the handshake
The WebSocket handshake
Focus on the following fields through packet capture cloud WebSocket request
The above is to initiate the WebSocekt request packet capture, first pay attention to the more than HTTP values:
// Tell the server that the service initiates the WebSocket protocol and needs WebSocket processing
Upgrade: websocket
Connection: Upgrade
Copy the code
Sec-WebSocket-Key: aI0TsvW7jltfmNOF+1eSqg== // Base64, randomly generated by the browser. Provides basic protection in conjunction with sec-websocket-Accept of the subsequent server response. Like malicious connections, or unintentional connections
Sec-WebSocket-Version: 13 // Indicates the websocket version. If the server does not support the version, you need to return an sec-websocket-versionheader containing the version number supported by the server
Copy the code
Check Response Headers:
Sec-WebSocket-Accept: OfEosYlCAcvV/jdwbW33VU0B50k= // Security verification. Base64 (sha1($sec-websocket-Accept,' 258eafa5-e914-47DA-95ca-C5AB0DC85b11 '))
Copy the code
// Inform the client that the upgrade to WebSocket is successful
Upgrade: websocket
Connection: Upgrade
Copy the code
alternative
Browsers don’t have a perfect alternative to WebSocket. The simulation can only be done with Ajax polling or long polling, both of which have performance issues and cost resources
Ajax polling, long training in rotation: zhuanlan.zhihu.com/p/25690011