Recently used Tornado to make long links think about how to try to try the WebSocket protocol. So do what you say.
The first thing to know is that WebSocket is based on the HTTP protocol, why do you say so? Because from the protocol, WebSocket is borrowing part of the HTTP request header information for authentication and request.
Let's look at a standard WebSocket request header:
---request header---/chat http/1.1127.0.0.1:8001origin:http:// 127.0.0.1:8001sec-websocket-key:hj0enqbhe/a0gkbxdrryyw==sec-websocket-version:13
Can be seen using the http1.1 protocol above is the standard HTTP request information
Method URL Http_protocol_versionshostconnection
But it is clear that some of the information here is more than a small partner familiar with HTTP. Used to implement protocol upgrades
Upgrade:websocketConnection:Upgrade
Origin:xxxx
Sec-websocket-key:hj0enqbhe/a0gkbxdrryyw==sec-websocket-version:13
Upgrade WebSocket is used to tell the server that this connection needs to be upgraded to WebSocket.
And the following sec-websocket-key is the client is the browser or other terminal randomly generated a set of 16-bit random base64 encoded string sent up here to paste the websocket-client I found in this library to generate this key function.
def _create_sec_websocket_key (): = Os.urandom (+) return base64encode (randomness). Decode ('utf-8' ). Strip ()
The last Sec-websocket-version is the version number of the current usage protocol.
After receiving the above request, the server will reverse a response header package to complete the handshake.
http/1.1 101 Switching protocolscontent-length:0upgrade:websocketsec-websocket-accept:zes+c+ vbk8aj01+wjgn7y15796g=server:tornadoserver/4.5.1June 03:29:14 GMT
The checksum is completed by Sec-websocket-accept key. I'm pasting a generated sec-websocket-accept code, everybody, feel it.
def Compute_accept_value (Key): """ computes the value for the sec-websocket-accept header, given the value for Sec-websocket-key. """ = Hashlib.sha1 () sha1.update (UTF8 (key)) Sha1.update (b" 258EAFA5-E914-47DA-95CA-C5AB0DC85B11") # Magic value Return native_str (Base64.b64encode (Sha1.digest ()))
This key is the Sec_key that the client sends up. The server then calculates the SHA1 and can find this in a GUID RFC6455. The Base64Encode is then returned to the client. The client takes its own key to do the same encryption, if the handshake is completed. This is where you can start communicating happily with WebSocket!
This is the end of this article, if you want to understand the WebSocket protocol and the traditional long poll and short poll between the difference and use the scene, you can see the first in reference. That was very detailed and interesting. In this article will not repeat.
Reference:
https://www.zhihu.com/question/20215561 WebSocket is the principle of why a persistent connection can be achieved.
https://tools.ietf.org/html/rfc6455 RFC6455
WebSocket Protocol Handshake