Python 服务器 Websocket 握手响应

Python Server Websocket Handshake Response

我想知道如何响应 Python 中的 javascript websocket 握手 3,我似乎无法弄清楚我应该如何在服务器端响应。我从我的客户网页收到了这个请求:

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

我可以说我可能不会关心其中的大部分内容,我只需要知道要发送什么 HTTP headers 等,以便我可以设置此 websocket。谢谢!

从此处的 Python2 代码转换而来:https://gist.github.com/jkp/3136208

这是服务器端 Python3 验证客户端浏览器的代码 & return 它是握手确认:

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'))