内置 WebSockets: 接受未掩码的客户端帧 (RFC 6455 §5.1)
作者: UWCSZhou创建于 2026年8月10日更新于 2026年8月31日
标签Status: Available
运行一个带有 WebSocket 监听器的代理程序:
listener 1884 127.0.0.1
protocol websockets
allow_anonymous true
persistence false最小的自包含的重现程序(Python 仅使用标准库),还附带为 mini_repro.py:
import base64, os, socket, struct, sys, time
host = sys.argv[1] if len(sys.argv) > 1 else "127.0.0.1"
port = int(sys.argv[2]) if len(sys.argv) > 2 else 1884
def ws(payload, mask=True, opcode=0x2):
b = bytes([0x80 | opcode]); n = len(payload); mb = 0x80 if mask else 0x00
b += bytes([mb | n]) if n < 126 else bytes([mb | 126]) + struct.pack("!H", n)
if not mask: return b + payload
k = os.urandom(4); return b + k + bytes(c ^ k[i % 4] for i, c in enumerate(payload))
def mqtt(cmd, body): return bytes([cmd, len(body)]) + body
def s(x): return struct.pack("!H", len(x)) + x.encode()
def connect(cid): return mqtt(0x10, s("MQTT")+bytes([5,2])+struct.pack("!H",60)+b"\x00"+s(cid))
def handshake(sock):
key = base64.b64encode(os.urandom(16)).decode()
sock.sendall((f"GET /mqtt HTTP/1.1\r\nHost: {host}\r\nUpgrade: websocket\r\n"
f"Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\n"
f"Sec-WebSocket-Version: 13\r\nSec-WebSocket-Protocol: mqtt\r\n\r\n").encode())
time.sleep(0.2); sock.recv(4096)
def connack_ok(r):
i = r.find(b"\x20"); return i != -1 and i+3 < len(r) and r[i+3] == 0x00
# unmasked CONNECT as the first
…内容来源: eclipse-mosquitto/mosquitto