Python通過websocket與js客戶端通信示例分析
具體的 websocket 介紹可見 http://zh.wikipedia.org/wiki/WebSocket
這里,介紹如何使用 Python 與前端 js 進(jìn)行通信。
websocket 使用 HTTP 協(xié)議完成握手之后,不通過 HTTP 直接進(jìn)行 websocket 通信。
于是,使用 websocket 大致兩個(gè)步驟:使用 HTTP 握手,通信。
js 處理 websocket 要使用 ws 模塊; Python 處理則使用 socket 模塊建立 TCP 連接即可,比一般的 socket ,只多一個(gè)握手以及數(shù)據(jù)處理的步驟。
握手
過程

包格式
js 客戶端先向服務(wù)器端 python 發(fā)送握手包,格式如下:
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
服務(wù)器回應(yīng)包格式:
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= Sec-WebSocket-Protocol: chat
其中, Sec-WebSocket-Key 是隨機(jī)的,服務(wù)器用這些數(shù)據(jù)構(gòu)造一個(gè) 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 的類,初始化后自動(dòng)發(fā)送握手包,如下:
var socket = new WebSocket('ws://localhost:3368');
Python 端
Python 用 socket 接受得到握手字符串,處理后發(fā)送
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
#這里省略監(jiān)聽,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
通信
不同版本的瀏覽器定義的數(shù)據(jù)幀格式不同, Python 發(fā)送和接收時(shí)都要處理得到符合格式的數(shù)據(jù)包,才能通信。
Python 接收
Python 接收到瀏覽器發(fā)來的數(shù)據(jù),要解析后才能得到其中的有用數(shù)據(jù)。
瀏覽器包格式

固定字節(jié):
( 1000 0001 或是 1000 0002 )這里沒用,忽略
包長(zhǎng)度字節(jié):
第一位肯定是 1 ,忽略。剩下 7 個(gè)位可以得到一個(gè)整數(shù) (0 ~ 127) ,其中
( 1-125 )表此字節(jié)為長(zhǎng)度字節(jié),大小即為長(zhǎng)度;
(126)表接下來的兩個(gè)字節(jié)才是長(zhǎng)度;
(127)表接下來的八個(gè)字節(jié)才是長(zhǎng)度;
用這種變長(zhǎng)的方式表示數(shù)據(jù)長(zhǎng)度,節(jié)省數(shù)據(jù)位。
mark 掩碼:
mark 掩碼為包長(zhǎng)之后的 4 個(gè)字節(jié),之后的兄弟數(shù)據(jù)要與 mark 掩碼做運(yùn)算才能得到真實(shí)的數(shù)據(jù)。
兄弟數(shù)據(jù):
得到真實(shí)數(shù)據(jù)的方法:將兄弟數(shù)據(jù)的每一位 x ,和掩碼的第 i%4 位做 xor 運(yùn)算,其中 i 是 x 在兄弟數(shù)據(jù)中的索引。
完整代碼
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 對(duì)象,通過 ws.send(str) 即可發(fā)送
ws.send(str)
Python 發(fā)送
Python 要包數(shù)據(jù)發(fā)送,也需要處理,發(fā)送包格式如下

固定字節(jié):固定的 1000 0001( ‘ \x81 ′ )
包長(zhǎng):根據(jù)發(fā)送數(shù)據(jù)長(zhǎng)度是否超過 125 , 0xFFFF(65535) 來生成 1 個(gè)或 3 個(gè)或 9 個(gè)字節(jié),來代表數(shù)據(jù)長(zhǎng)度。
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中處理二進(jìn)制數(shù)的模塊,二進(jìn)制流為C,或網(wǎng)絡(luò)流的形式。
data = '%s%s' % (token, data)
self.con.send(data)
return True
js 端通過回調(diào)函數(shù) ws.onmessage() 接受數(shù)據(jù)
ws.onmessage = function(result,nTime){
alert("從服務(wù)端收到的數(shù)據(jù):");
alert("最近一次發(fā)送數(shù)據(jù)到現(xiàn)在接收一共使用時(shí)間:" + nTime);
console.log(result);
}
最終代碼
Python服務(wù)端
# _*_ 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中處理二進(jìn)制數(shù)的模塊,二進(jìn)制流為C,或網(wǎng)絡(luò)流的形式。
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)
#鏈接隊(duì)列大小
print "bind 3368,ready to use"
except:
print("Server is already running,quit")
sys.exit()
while True:
connection, address = sock.accept()
#返回元組(socket,add),accept調(diào)用時(shí)會(huì)進(jìn)入waite狀態(tài)
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("從服務(wù)端收到的數(shù)據(jù):");
alert("最近一次發(fā)送數(shù)據(jù)到現(xiàn)在接收一共使用時(shí)間:" + nTime);
console.log(result);
}
</script>
- Python Websocket服務(wù)端通信的使用示例
- 使用python構(gòu)建WebSocket客戶端的教程詳解
- python實(shí)現(xiàn)WebSocket服務(wù)端過程解析
- 詳解python websocket獲取實(shí)時(shí)數(shù)據(jù)的幾種常見鏈接方式
- python實(shí)現(xiàn)websocket的客戶端壓力測(cè)試
- Python如何爬取實(shí)時(shí)變化的WebSocket數(shù)據(jù)的方法
- python制作websocket服務(wù)器實(shí)例分享
- Python 實(shí)現(xiàn) WebSocket 通信的過程詳解
相關(guān)文章
細(xì)數(shù)nn.BCELoss與nn.CrossEntropyLoss的區(qū)別
今天小編就為大家整理了一篇細(xì)數(shù)nn.BCELoss與nn.CrossEntropyLoss的區(qū)別,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-02-02
解決Python 爬蟲URL中存在中文或特殊符號(hào)無法請(qǐng)求的問題
今天小編就為大家分享一篇解決Python 爬蟲URL中存在中文或特殊符號(hào)無法請(qǐng)求的問題。這種問題,初學(xué)者應(yīng)該都會(huì)遇到,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-05-05
利用PyInstaller將python程序.py轉(zhuǎn)為.exe的方法詳解
這篇文章主要給大家介紹了利用PyInstaller將python程序.py轉(zhuǎn)為.exe的方法,文中介紹的非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起看看吧。2017-05-05
mac安裝scrapy并創(chuàng)建項(xiàng)目的實(shí)例講解
今天小編就為大家分享一篇mac安裝scrapy并創(chuàng)建項(xiàng)目的實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-06-06
Python實(shí)現(xiàn)對(duì)文件進(jìn)行單詞劃分并去重排序操作示例
這篇文章主要介紹了Python實(shí)現(xiàn)對(duì)文件進(jìn)行單詞劃分并去重排序操作,涉及Python文件讀取、字符串遍歷、拆分、排序等相關(guān)操作技巧,需要的朋友可以參考下2018-07-07
python中if的基礎(chǔ)用法(if?else和if?not)
if在Python中用作某個(gè)條件或值的判斷,下面這篇文章主要給大家介紹了關(guān)于python中if的基礎(chǔ)用法,主要包括if?else和if?not,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2022-09-09
Python實(shí)現(xiàn)將圖像轉(zhuǎn)換為ASCII字符圖
使用Python進(jìn)行圖像處理,非??旖莘奖?,往往簡(jiǎn)短幾行代碼就可以實(shí)現(xiàn)功能強(qiáng)大的效果。在這篇文章中,我們將使用Python將圖像轉(zhuǎn)換為ASCII字符照,感興趣的可以了解一下2022-08-08
Python巧用SnowNLP實(shí)現(xiàn)生成srt字幕文件
SnowNLP是一個(gè)可以方便的處理中文文本內(nèi)容的python類庫,本文主要為大家詳細(xì)介紹了Python如何巧用SnowNLP實(shí)現(xiàn)將一段話一鍵生成srt字幕文件,感興趣的可以了解下2024-01-01
使用Python創(chuàng)建快捷方式管理應(yīng)用
在Windows系統(tǒng)中,快速訪問常用程序通常通過“開始菜單”中的“應(yīng)用熱門”功能實(shí)現(xiàn),在這篇博客中,我將向你展示如何使用Python和wxPython創(chuàng)建一個(gè)GUI應(yīng)用,幫助用戶輕松將桌面上的快捷方式添加到Windows“開始菜單”的“應(yīng)用熱門”中,需要的朋友可以參考下2024-08-08

