Python 服务器 Websocket 握手响应
Posted
技术标签:
【中文标题】Python 服务器 Websocket 握手响应【英文标题】:Python Server Websocket Handshake Response 【发布时间】:2015-06-08 22:25:17 【问题描述】:我想知道如何响应 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】:这里是从 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'))
【讨论】:
以上是关于Python 服务器 Websocket 握手响应的主要内容,如果未能解决你的问题,请参考以下文章