Python--websocket Data parsing

Source: Internet
Author: User
Tags pack sha1 sha1 encryption string back pprint

# 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 (1024x768) ' >>> 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 ') # can also send data def send_msg (Conn, msg_bytes): "" "WebSocket the server sends a message to the client:P Aram Conn: The client connects to the servers-side socket pair    Image, i.e.: Conn,address = socket.accept ():p Aram Msg_bytes: Bytes sent to client: return: "" "Import struct token = B" \X81 "        length = Len (msg_bytes) if length < 126:token + = Struct.pack ("B", length) elif length <= 0xFFFF: Token + = Struct.pack ("! BH ", 126, length) Else:token + = Struct.pack ("!     BQ ", 127, Length) msg = token + msg_bytes conn.send (msg) return true# then you can accept the data, note that the accepted data must follow certain rules to obtain while True: info = conn.recv (1024x768) Payload_len = info[1] & 127 if Payload_len = = 126:extend_payload_len = info[2        : 4] mask = Info[4:8] decoded = info[8:] elif Payload_len = = 127:extend_payload_len = Info[2:10]        mask = info[10:14] decoded = info[14:] Else:extend_payload_len = None mask = info[2:6] decoded = info[6:] bytes_list = ByteArray () for I in Range (len (decoded)): Chunk = decoded[i] ^ mask[i% 4] bytes_list.append (chunk) BODY = str (bytes_list, en coding= ' Utf-8 ') print (body) # can get the body plus the new character BODY = body + "I'm Your Dad" send_msg (conn, bytes (body, encoding= "utf-8 "))

  

Unpacking process: (This figure from Wudang Sir Teacher's blog: https://www.cnblogs.com/wupeiqi/p/6558766.html)

0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1+-+-+-+-+-------+-+-------------+-------------------------------+| F| r| r| r| opcode| m|    Payload Len | Extended Payload Length | | i| s| s|  s| (4) |     a|             (7) | (16/64) | | n| v| v|       v| |             s|   | (if payload len==126/127) | |       |1|2|3| |             k|                               |     |+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +| Extended payload length continued, if payload len = = 127 |+----------------------------------------------                               -+| | Masking-key, if MASK set to 1 |+-------------------------------+-------------------------------+|          Masking-key (continued) | Payload Data |+-----------------------------------------------+: Payload data Continued ...: +--------------- - - - - - - - - - - - - - - - - +| Payload Data Continued ... | +---------------------------------------------------------------+

  

<! DOCTYPE html>

  

  

  

Python--websocket Data parsing

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.