环境:Python 3.6.5,Chrome 81.0.4044.138
说明:并非直接使用websockets模块来编写
0x00 前言
公司项目中有很多要求实时状态的功能,且响应数据很小。现有方式采用ajax轮询,较浪费资源,故开始探索socket编程。此文仅为初步探索,实现功能仅为client -> server -> client
。
0x01 参考文章
Python 3.5.2实现websocket服务端
用Python实现一个简单的WebSocket服务器
易百教程:Websocket教程™
0x02 服务端代码
# 文件名:Server.py
import socket
import threading
import hashlib
import base64
import struct
import time
PRINT_LOG = True
GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
# 将由js提交的bytes类型的消息转为str
def bytes2str(msg):
local_code_length = msg[1] & 127
if local_code_length == 126:
masks = msg[4:8]
data = msg[8:]
elif local_code_length == 127:
masks = msg[10:14]
data = msg[14:]
else:
masks = msg[2:6]
data = msg[6:]
en_bytes = b""
cn_bytes = []
for i, d in enumerate(data):
nv = chr(d ^ masks[i % 4])
nv_bytes = nv.encode()
nv_len = len(nv_bytes)
if nv_len == 1:
en_bytes += nv_bytes
else:
en_bytes += b'%s'
cn_bytes.append(ord(nv_bytes.decode()))
if len(cn_bytes) > 2:
cn_str = ""
cn_len = len(cn_bytes)
count = int(cn_len / 3)
for x in range(count):
i = x * 3
b = bytes([cn_bytes[i], cn_bytes[i + 1], cn_bytes[i + 2]])
cn_str += b.decode()
new = en_bytes.replace(b'%s%s%s', b'%s')
new = new.decode()
rst = (new % tuple(list(cn_str)))
else:
rst = en_bytes.decode()
return rst
# 根据js发送的报文计算code_length和header_length并返回
def calculate_data_length(msg):
local_code_length = msg[1] & 127
if local_code_length == 126:
local_code_length = struct.unpack('>H', msg[2:4])[0]
local_header_length = 8
elif local_code_length == 127:
local_code_length = struct.unpack('>Q', msg[2:10])[0]