Python服务器Websocket握手响应

时间:2015-06-08 22:25:18

标签: javascript python http websocket server

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

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头文件和发送内容,以便我可以设置这个websocket。谢谢!

1 个答案:

答案 0 :(得分:1)

在这里转换自Python2代码:https://gist.github.com/jkp/3136208

这是用于验证客户端浏览器和服务器端的服务器端Python3代码。给它一个握手确认:

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