# WebSocket Implementation principle ' 1. The server opens the socket, listens on the IP and Port 2. Client sends connection request (with IP and port) 3. Server-side allow connection 4. The client generates a random string, and the magic string is combined to perform a SHA1 encryption, encryption. and sends a random string to the server 5. The server is then encrypted in the same way. 6. The server then returns the encrypted string back to the client 7. The client makes a comparison between the secret string returned by the server and its own encrypted string, and, if the same, follows the same protocol. If it's not the same, you can't play. Import socketimport base64import hashlibfrom pprint import pprintdef get_headers (data): "" Formats the request header into a dictionary:p Aram dat A:: Return: "" "header_dict = {} data = str (data, encoding= ' Utf-8 ') header, BODY = data.split (' \r\n\r\n ', 1 ) Header_list = Header.split (' \ r \ n ') for I in range (0, Len (header_list)): if i = = 0:if Len (header _list[i].split (")) = = 3:header_dict[' method '], header_dict[' url '], header_dict[' protocol '] = Header_list [I].split (') else:k, V = header_list[i].split (': ', 1) header_dict[k] = V.strip () return Header_dictserver = Socket.socket (socket.af_inet, socket. Sock_stream) server.bind ((' localhost ', 8080)) Server.listen (5) # Waiting for user connection conn, addr = server.accept () # Handshake message COntent = CONN.RECV (8096) ">>> print (content) B ' Get/http/1.1\r\nhost:localhost:8080\r\nconnection:upgrade \r\npragma:no-cache\r\ncache-control:no-cache\r\nupgrade:websocket\r\norigin:http://localhost:63342\r\ nsec-websocket-version:13\r\nuser-agent:mozilla/5.0 (Windows NT 10.0; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/67.0.3396.99 safari/537.36\r\naccept-encoding:gzip, deflate, br\r \NACCEPT-LANGUAGE:ZH-CN,ZH;Q=0.9\R\NCOOKIE:UUID=81A68694C772E0C62D4A5A3C256FE3E0; sensorsdata2015jssdkcross=%7b%22distinct_id%22%3a% 2216453a8bf2bbe-09a40e8e58a866-5e442e19-1fa400-16453a8bf2c745%22%7d; hm_lvt_2af69bc2b378fb58ae04ed2a04257ed1=1530411925; Pycharm-bdfc5fce=a920e49d-da4e-4d2f-a76e-17acfacc6462\r\nsec-websocket-key:1y6wpssgff80wqi3hpmrqq==\r\ Nsec-websocket-extensions:permessage-deflate; client_max_window_bits\r\n\r\n ' # GET request Header headers = get_headers (content) ' >>>pprint (headers) {' Cache-control ': ' No-cache ', ' Connection ': ' Upgrade ', ' Cookie ': ' pycharm-bdfc5fce=a920e49d-da4e-4d2f-a76e-17acfacc6462 ', ' Host ': ' localhost:8080 ', ' Origin ': ' http://localhost:63342 ', ' Sec-websocket-key ': ' rrgdeyeysgep9ehy85u8oq== ', ' sec-websocket-version ': ' A ', ' Upgrade ': ' WebSocket ', ' user-agent ': ' mozilla/5.0 (Windows NT 10.0; WOW64; trident/7.0; rv:11.0) ' Like Gecko ', ' method ': ' GET ', ' protocol ': ' http/1.1 ', ' url ': '/'} ' # rule: The Magic string is called this magic_string = "258eafa5-e914-47da-95ca-c5ab0dc85b11" # Gets the random string and combines it with a magical string of value = headers["Sec-websocket-key" + magic_string# for encryption, Hash_str = Base64.b64encode (hashlib.sha1 (bytes (value, encoding= ' Utf-8 ')) only in accordance with this encryption. Digest ()) RESPONSE_TPL = "http/ 1.1 101 Switching protocols\r\n "" upgrade:websocket\r\n "" connection:upgrade\r\n " "Sec-websocket-accept:%s\r\n" "websocket-location:ws://%s%s\r\n\r\n" # Get handshake messages, combine magic strings, make SHA1 encryption # sent to guest Client Response_str = response_tpl% (str (hash_str, encoding= ' Utf-8 '), headers[' Host '], headers[' url ']) conn.send (bytes ( RESPONSE_STR, Encoding= ' Utf-8 '))
<! DOCTYPE html>
Python implementation WebSocket