我想知道如何响应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了。谢谢!
发布于 2015-11-30 22:56:50
从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'))https://stackoverflow.com/questions/30720111
复制相似问题