具體的 websocket 介紹可見 http://zh.wikipedia.org/wiki/WebSocket
這里,介紹如何使用 Python 與前端 js 進行通信。
websocket 使用 HTTP 協議完成握手之后,不通過 HTTP 直接進行 websocket 通信。
于是,使用 websocket 大致兩個步驟:使用 HTTP 握手,通信。
js 處理 websocket 要使用 ws 模塊; Python 處理則使用 socket 模塊建立 TCP 連接即可,比一般的 socket ,只多一個握手以及數據處理的步驟。
握手
過程
包格式
js 客戶端先向服務器端 python 發送握手包,格式如下:
GET /chat HTTP/1.1Host: server.example.comUpgrade: websocketConnection: UpgradeSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==Origin: http://example.comSec-WebSocket-Protocol: chat, superchatSec-WebSocket-Version: 13
服務器回應包格式:
HTTP/1.1 101 Switching ProtocolsUpgrade: websocketConnection: UpgradeSec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=Sec-WebSocket-Protocol: chat
其中, Sec-WebSocket-Key 是隨機的,服務器用這些數據構造一個 SHA-1 信息摘要。
方法為: key+migic , SHA-1 加密, base-64 加密,如下:
Python 中的處理代碼
MAGIC_STRING = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'res_key = base64.b64encode(hashlib.sha1(sec_key + MAGIC_STRING).digest())
握手完整代碼
js 端
js 中有處理 websocket 的類,初始化后自動發送握手包,如下:
var socket = new WebSocket('ws://localhost:3368');
Python 端
Python 用 socket 接受得到握手字符串,處理后發送
HOST = 'localhost'PORT = 3368MAGIC_STRING = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'HANDSHAKE_STRING = "HTTP/1.1 101 Switching Protocols/r/n" / "Upgrade:websocket/r/n" / "Connection: Upgrade/r/n" / "Sec-WebSocket-Accept: {1}/r/n" / "WebSocket-Location: ws://{2}/chat/r/n" / "WebSocket-Protocol:chat/r/n/r/n" def handshake(con):#con為用socket,accept()得到的socket#這里省略監聽,accept的代碼,具體可見blog:http://blog.csdn.net/ice110956/article/details/29830627 headers = {} shake = con.recv(1024) if not len(shake): return False header, data = shake.split('/r/n/r/n', 1) for line in header.split('/r/n')[1:]: key, val = line.split(': ', 1) headers[key] = val if 'Sec-WebSocket-Key' not in headers: print ('This socket is not websocket, client close.') con.close() return False sec_key = headers['Sec-WebSocket-Key'] res_key = base64.b64encode(hashlib.sha1(sec_key + MAGIC_STRING).digest()) str_handshake = HANDSHAKE_STRING.replace('{1}', res_key).replace('{2}', HOST + ':' + str(PORT)) print str_handshake con.send(str_handshake)return True
新聞熱點
疑難解答