WebSocket相关
原文:http://www.cnblogs.com/jinjiangongzuoshi/p/5062092.html
前言
今天看了一些資料,記錄一下心得。websocket是html5引入的一個新特性,傳統(tǒng)的web應(yīng)用是通過http協(xié)議來提供支持,如果要實時同步傳輸數(shù)據(jù),需要輪詢,效率低下websocket是類似socket通信,web端連接服務(wù)器后,握手成功,一直保持連接,可以理解為長連接,這時服務(wù)器就可以主動給客戶端發(fā)送數(shù)據(jù),實現(xiàn)數(shù)據(jù)的自動更新。使用websocket需要注意瀏覽器和當(dāng)前的版本,不同的瀏覽器提供的支持不一樣,因此設(shè)計服務(wù)器的時候,需要考慮。?
進(jìn)一步簡述
?
websocket是一個瀏覽器和服務(wù)器通信的新的協(xié)議,一般而言,瀏覽器和服務(wù)器通信最常用的是http協(xié)議,但是http協(xié)議是無狀態(tài)的,每次瀏覽器請求信息,服務(wù)器返回信息后這個瀏覽器和服務(wù)器通信的信道就被關(guān)閉了,這樣使得服務(wù)器如果想主動給瀏覽器發(fā)送信息變得不可能了,服務(wù)器推技術(shù)在http時代的解決方案一個是客戶端去輪詢,或是使用comet技術(shù),而websocket則和一般的socket一樣,使得瀏覽器和服務(wù)器建立了一個雙工的通道。 具體的websocket協(xié)議在rfc6455里面有,這里簡要說明一下。websocket通信需要先有個握手的過程,使得協(xié)議由http轉(zhuǎn)變?yōu)閣ebscoket協(xié)議,然后瀏覽器和服務(wù)器就可以利用這個socket來通信了。首先瀏覽器發(fā)送握手信息,要求協(xié)議轉(zhuǎn)變?yōu)閣ebsocketGET / HTTP/1.1 Host: example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: http://example.com 服務(wù)器接收到信息后,取得其中的Sec-WebSocket-Key,將他和一個固定的字符串258EAFA5-E914-47DA-95CA-C5AB0DC85B11做拼接,得到的字符串先用sha1做一下轉(zhuǎn)換,再用base64轉(zhuǎn)換一下,就得到了回應(yīng)的字符串,這樣服務(wù)器端發(fā)送回的消息是這樣的HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= 這樣握手就完成了,用python來實現(xiàn)這段握手過程的話就是下面這樣。def handshake(conn):key =Nonedata = conn.recv(8192)if not len(data):return Falsefor line in data.split('\r\n\r\n')[0].split('\r\n')[1:]:k, v = line.split(': ')if k =='Sec-WebSocket-Key':key =base64.b64encode(hashlib.sha1(v +'258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest())if not key:conn.close()return Falseresponse ='HTTP/1.1 101 Switching Protocols\r\n'\'Upgrade: websocket\r\n'\'Connection: Upgrade\r\n'\'Sec-WebSocket-Accept:'+ key +'\r\n\r\n'conn.send(response)return True 握手過程完成之后就是信息傳輸了,websocket的數(shù)據(jù)信息格式是這樣的。+-+-+-+-+-------+-+-------------+-------------------------------+0 1 2 30 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-------+-+-------------+-------------------------------+ |F|R|R|R| opcode|M| Payload len | Extended payload length | |I|S|S|S| (4) |A| (7) | (16/64) | |N|V|V|V| |S| | (if payload len==126/127) | | |1|2|3| |K| | | +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + | Extended payload length continued, if payload len == 127 | + - - - - - - - - - - - - - - - +-------------------------------+ | | Masking-key, if MASK set to 1 | +-------------------------------+-------------------------------+ | Masking-key (continued) | Payload Data | +-------------------------------- - - - - - - - - - - - - - - - + : Payload Data continued ... : + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + | Payload Data continued ... | +---------------------------------------------------------------+ 值得注意的是payload len這項,表示數(shù)據(jù)的長度有多少,如果小于126,那么payload len就是數(shù)據(jù)的長度,如果是126那么接下來2個字節(jié)是數(shù)據(jù)長度,如果是127表示接下來8個字節(jié)是數(shù)據(jù)長度,然后后面會有四個字節(jié)的mask,真實數(shù)據(jù)要由payload data和mask做異或才能得到,這樣就可以得到數(shù)據(jù)了。發(fā)送數(shù)據(jù)的格式和接受的數(shù)據(jù)類似,具體細(xì)節(jié)可以去參考rfc6455,這里就不過多贅述了。?
Python的Websocket客戶端:Websocket-Client
?
?
Websocket-Client 是 Python 上的 Websocket 客戶端。它只支持 hybi-13,且所有的 Websocket API 都支持同步。Installation
This module is tested on Python 2.7 and Python 3.x.
Type "python setup.py install" or "pip install websocket-client" to install.
Caution!
from v0.16.0, we can install by "pip install websocket-client" for python 3.
This module depend on
- six
- backports.ssl_match_hostname for Python 2.x
?
?
Python通過websocket與js客戶端通信示例分析
這里,介紹如何使用 Python 與前端 js 進(jìn)行通信。
websocket 使用 HTTP 協(xié)議完成握手之后,不通過 HTTP 直接進(jìn)行 websocket 通信。
于是,使用 websocket 大致兩個步驟:使用 HTTP 握手,通信。
js 處理 websocket 要使用 ws 模塊; Python 處理則使用 socket 模塊建立 TCP 連接即可,比一般的 socket ,只多一個握手以及數(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)造一個 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 的類,初始化后自動發(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ù)據(jù)包,才能通信。
Python 接收
Python 接收到瀏覽器發(fā)來的數(shù)據(jù),要解析后才能得到其中的有用數(shù)據(jù)。
?
固定字節(jié):
( 1000 0001 或是 1000 0002 )這里沒用,忽略
包長度字節(jié):
第一位肯定是 1 ,忽略。剩下 7 個位可以得到一個整數(shù) (0 ~ 127) ,其中
( 1-125 )表此字節(jié)為長度字節(jié),大小即為長度;
(126)表接下來的兩個字節(jié)才是長度;
(127)表接下來的八個字節(jié)才是長度;
用這種變長的方式表示數(shù)據(jù)長度,節(jié)省數(shù)據(jù)位。
mark 掩碼:
mark 掩碼為包長之后的 4 個字節(jié),之后的兄弟數(shù)據(jù)要與 mark 掩碼做運(yùn)算才能得到真實的數(shù)據(jù)。
兄弟數(shù)據(jù):
得到真實數(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_strjs 端的 ws 對象,通過 ws.send(str) 即可發(fā)送
ws.send(str)
?
Python 發(fā)送
Python 要包數(shù)據(jù)發(fā)送,也需要處理
固定字節(jié):固定的 1000 0001( ‘ \x81 ′ )
包長:根據(jù)發(fā)送數(shù)據(jù)長度是否超過 125 , 0xFFFF(65535) 來生成 1 個或 3 個或 9 個字節(jié),來代表數(shù)據(jù)長度。
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)在接收一共使用時間:" + 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) #鏈接隊列大小 print "bind 3368,ready to use" except: print("Server is already running,quit") sys.exit() while True: connection, address = sock.accept() #轉(zhuǎn)載于:https://www.cnblogs.com/DI-DIAO/p/9246344.html
總結(jié)
以上是生活随笔為你收集整理的WebSocket相关的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。