Background
Previously, many websites used polling to implement push technology. Polling is at a specific time interval (for example, 1 seconds), the browser sends an HTTP request to the server, and the server returns the latest data to the browser. The disadvantage of polling is obvious, the browser needs to constantly make requests to the server, however, the header of the HTTP request is very long, and the actual transmission of data may be very small, resulting in a waste of bandwidth and server resources.
Comet uses Ajax to improve polling, enabling two-way communication. But comet still needs to make a request, and in comet, long links are widely used, which also consumes server bandwidth and resources.
As a result, the WebSocket agreement arose.
WebSocket protocol
The browser makes a request to the server to establish a WebSocket connection through JavaScript, and after the connection is established, the client and server Exchange data directly over the TCP connection. The WebSocket connection is essentially a TCP connection.
WebSocket has a great performance advantage in terms of the stability of data transmission and the size of data transmission volume. Websocket.org compared the performance benefits of polling and Websocket:
As can be seen, the WebSocket has a great performance advantage, the flow and load increase in the case of more obvious advantages.
Example
Browser request
GET / HTTP/1.1Upgrade: websocketConnection: UpgradeHost: example.comOrigin: nullSec-WebSocket-Key: sN9cRrP/n9NdMgdcy2VJFQ==Sec-WebSocket-Version: 13
Server response
HTTP/1.1 101 Switching ProtocolsUpgrade: websocketConnection: UpgradeSec-WebSocket-Accept: fFBooB7FAkLlXgRSz0BT3v4hq5s=Sec-WebSocket-Origin: nullSec-WebSocket-Location: ws://example.com/
In the request Sec-WebSocket-Key
is random, the server side will use this data to construct a SHA-1 information digest. Sec-WebSocket-Key
Add a magic string 258EAFA5-E914-47DA-95CA-C5AB0DC85B11
. Using SHA-1 encryption, the BASE-64 encoding is followed, and the result is Sec-WebSocket-Accept
returned to the client as the value of the header.
Python Code implementation
def ws_accept_key (Ws_key): "" " Calc the sec-websocket-accept key by Sec-websocket-key come from client, the Return value used for handshake : Ws_key:sec-websocket-key come from client : Returns:sec-websocket-accept "" " import hashlib import base64 try: magic = ' 258EAFA5-E914-47DA-95CA-C5AB0DC85B11 ' SHA1 = HASHLIB.SHA1 () sha1.update (Ws_key + Magic) return Base64.b64encode (Sha1.digest ()) except Exception As e: return noneprint ws_accept_key (' sn9crrp/n9ndmgdcy2vjfq== ')
Python simulates the websocket handshake during a sec-websocket-accept calculation