简体   繁体   中英

Python Server Websocket Handshake Response

I was wondering how to respond to a javascript websocket handshake in Python 3, I can't seem to figure out how I should respond on the server side of things. I got this request from my client webpage:

GET / HTTP/1.1
Host: localhost:8080
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
Origin: http://www.w3schools.com
Sec-WebSocket-Version: 13
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Sec-WebSocket-Key: euv7CmNNT22p59HbD3X7ww==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits

I can tell that I proably won't care about most of this, I just need to know what HTTP headers and such to send so that I can set this websocket up. Thanks!

Converted from Python2 code here: https://gist.github.com/jkp/3136208

Here is the server side Python3 code to verify client browser & return it an handshake confirmation:

MAGIC = b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'  # Fix key for handshake on server side
class WebSocketsHandler(socketserver.StreamRequestHandler):
   def handshake(self):
      data = self.request.recv(1024).strip()
      hsKey = hsUpgrade = b''
      for header in data.split(b'\r\n'):
         if header.startswith(b'Sec-WebSocket-Key'): hsKey = header.split(b':')[1].strip()
         if header.startswith(b'Upgrade'): hsUpgrade = header.split(b':')[1].strip()
      if hsUpgrade != b"websocket": return
      digest = b64encode(bytes.fromhex(sha1(hsKey + MAGIC).hexdigest())).decode('utf-8')
      response = ('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n'
            'Connection: Upgrade\r\nSec-WebSocket-Accept: {}\r\n\r\n'.format(digest))
      print('Handshaking...{}'.format(digest))
      self.handshake_done = self.request.send(response.encode('utf8'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM