[Python]通過websocket與jsclient通信
站點大多使用HTTP協議通信。而HTTP是無連接的協議。僅僅有client請求時,server端才幹發出對應的應答。HTTP請求的包也比較大,假設僅僅是非常小的數據通信。開銷過大。於是,我們能夠使用websocket這個協議,用最小的開銷實現面向連接的通信。
詳細的websocket介紹可見http://zh.wikipedia.org/wiki/WebSocket
這裏,介紹怎樣使用Python與前端js進行通信。
websocket使用HTTP協議完畢握手之後,不通過HTTP直接進行websocket通信。
於是,使用websocket大致兩個步驟:使用HTTP握手,通信。
js處理
握手
過程
包格式
jsclient先向server端python發送握手包,格式例如以下:
GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: http://example.com Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13
server回應包格式:
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= Sec-WebSocket-Protocol: chat
當中,Sec-WebSocket-Key是隨機的,server用這些數據構造一個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 = 3368 MAGIC_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
通信
不同版本號的瀏覽器定義的數據幀格式不同,Python發送和接收時都要處理得到符合格式的數據包,才幹通信。
Python接收
Python接收到瀏覽器發來的數據。要解析後才幹得到當中的實用數據。
瀏覽器包格式
固定字節:
(1000 0001或是1000 0002)這裏沒用,忽略
包長度字節:
第一位肯定是1。忽略。剩下7個位能夠得到一個整數(0 ~ 127),當中
(1-125)表此字節為長度字節。大小即為長度;
(126)表接下來的兩個字節才是長度;
(127)表接下來的八個字節才是長度;
用這樣的變長的方式表示數據長度,節省數據位。
mark掩碼:
mark掩碼為包長之後的4個字節,之後的兄弟數據要與mark掩碼做運算才幹得到真實的數據。
兄弟數據:
得到真實數據的方法:將兄弟數據的每一位x,和掩碼的第i%4位做xor運算,當中i是x在兄弟數據中的索引。
完整代碼
def recv_data(self, num): try: all_data = self.con.recv(num) if not len(all_data): return False except: return False else: code_len = ord(all_data[1]) & 127 if code_len == 126: masks = all_data[4:8] data = all_data[8:] elif code_len == 127: masks = all_data[10:14] data = all_data[14:] else: masks = all_data[2:6] data = all_data[6:] raw_str = "" i = 0 for d in data: raw_str += chr(ord(d) ^ ord(masks[i % 4])) i += 1 return raw_str
js端的ws對象,通過ws.send(str)就可以發送
ws.send(str)
Python發送
Python要包數據發送,也須要處理。發送包格式例如以下
固定字節:固定的1000 0001(‘\x81′)
包長:依據發送數據長度是否超過125,0xFFFF(65535)來生成1個或3個或9個字節,來代表數據長度。
def send_data(self, data): if data: data = str(data) else: return False token = "\x81" length = len(data) if length < 126: token += struct.pack("B", length) elif length <= 0xFFFF: token += struct.pack("!BH", 126, length) else: token += struct.pack("!BQ", 127, length) #struct為Python中處理二進制數的模塊,二進制流為C。或網絡流的形式。data = ‘%s%s‘ % (token, data) self.con.send(data) return True
js端通過回調函數ws.onmessage()接受數據
ws.onmessage = function(result,nTime){ alert("從服務端收到的數據:"); alert("近期一次發送數據到如今接收一共使用時間:" + nTime); console.log(result); }
終於代碼
Python服務端
# _*_ coding:utf-8 _*_ __author__ = ‘Patrick‘ import socket import threading import sys import os import MySQLdb import base64 import hashlib import struct # ====== config ====== HOST = ‘localhost‘ PORT = 3368 MAGIC_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" class Th(threading.Thread): def __init__(self, connection,): threading.Thread.__init__(self) self.con = connection def run(self): while True: try: pass self.con.close() def recv_data(self, num): try: all_data = self.con.recv(num) if not len(all_data): return False except: return False else: code_len = ord(all_data[1]) & 127 if code_len == 126: masks = all_data[4:8] data = all_data[8:] elif code_len == 127: masks = all_data[10:14] data = all_data[14:] else: masks = all_data[2:6] data = all_data[6:] raw_str = "" i = 0 for d in data: raw_str += chr(ord(d) ^ ord(masks[i % 4])) i += 1 return raw_str # send data def send_data(self, data): if data: data = str(data) else: return False token = "\x81" length = len(data) if length < 126: token += struct.pack("B", length) elif length <= 0xFFFF: token += struct.pack("!BH", 126, length) else: token += struct.pack("!BQ", 127, length) #struct為Python中處理二進制數的模塊,二進制流為C,或網絡流的形式。data = ‘%s%s‘ % (token, data) self.con.send(data) return True # handshake def handshake(con): 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 def new_service(): """start a service socket and listen when coms a connection, start a new thread to handle it""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.bind((‘localhost‘, 3368)) sock.listen(1000) #鏈接隊列大小 print "bind 3368,ready to use" except: print("Server is already running,quit") sys.exit() while True: connection, address = sock.accept() #返回元組(socket,add),accept調用時會進入waite狀態 print "Got connection from ", address if handshake(connection): print "handshake success" try: t = Th(connection, layout) t.start() print ‘new thread for client ...‘ except: print ‘start new thread error‘ connection.close() if __name__ == ‘__main__‘: new_service()
js客戶端
<script> var socket = new WebSocket(‘ws://localhost:3368‘); ws.onmessage = function(result,nTime){ alert("從服務端收到的數據:"); alert("近期一次發送數據到如今接收一共使用時間:" + nTime); console.log(result); } </script>
推薦blog
http://blog.csdn.net/fenglibing/article/details/7108982
http://blog.mycolorway.com/2011/11/22/a-minimal-python-websocket-server/
[Python]通過websocket與jsclient通信