2015-06-08 136 views
0

我想知道如何響應在Python 3中的JavaScript websocket握手,我似乎無法弄清楚我應該如何在服務器端做出響應。我從我的客戶端網頁申請:Python服務器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 

我可以告訴大家,我proably不會在意這個最,我只需要知道什麼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'))