From ea2d12c74ef700982c30d5f52e32cb8bfe357f1c Mon Sep 17 00:00:00 2001 From: wsy182 <2392948297@qq.com> Date: Fri, 14 Nov 2025 09:55:29 +0800 Subject: [PATCH] =?UTF-8?q?feat(network):=20=E6=B7=BB=E5=8A=A0=20WITS=20?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E6=8E=A5=E6=94=B6=E5=8A=9F=E8=83=BD=E5=B9=B6?= =?UTF-8?q?=E6=9B=B4=E6=96=B0=20WebSocket=20=E5=9C=B0=E5=9D=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 recive_wits.py 文件用于通过 TCP 接收 WITS 数据- 实现自动重连机制和数据黏包/拆包处理- 更新 test_websocket.py 中的 WebSocket 连接地址- 修改端口号以适配新的服务配置 --- recive_wits.py | 59 +++++++++++++++++++++++++++++++++++++++++++++++ test_websocket.py | 2 +- 2 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 recive_wits.py diff --git a/recive_wits.py b/recive_wits.py new file mode 100644 index 0000000..6109073 --- /dev/null +++ b/recive_wits.py @@ -0,0 +1,59 @@ +import socket +import time + +HOST = "192.168.1.41" +PORT = 9928 + +def connect(): + """建立 TCP 连接(带重试)""" + while True: + try: + print(f"Connecting to {HOST}:{PORT} ...") + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.connect((HOST, PORT)) + s.settimeout(5) + print("Connected successfully!") + return s + except Exception as e: + print(f"Connection failed: {e}, retrying in 3s...") + time.sleep(3) + + +def receive_wits_data(sock): + """持续接收 WITS 数据(自动处理黏包/拆包)""" + buffer = "" + + while True: + try: + data = sock.recv(4096) + + # 服务器关闭 + if not data: + print("Server closed connection.") + return False + + buffer += data.decode(errors="ignore") + + # WITS 多为 \r\n 分隔 + while "\n" in buffer: + line, buffer = buffer.split("\n", 1) + line = line.strip() + if line: + print("Received:", line) + + except socket.timeout: + # 正常情况,继续接收即可 + continue + except Exception as e: + print("Error:", e) + return False + + +if __name__ == "__main__": + while True: + sock = connect() + ok = receive_wits_data(sock) + sock.close() + + print("Reconnecting in 3 seconds...") + time.sleep(3) diff --git a/test_websocket.py b/test_websocket.py index 6a6cdee..62f31ac 100644 --- a/test_websocket.py +++ b/test_websocket.py @@ -1,7 +1,7 @@ import ssl import websocket -URL = "ws://192.168.1.41:9516/ws/" # 注意走 443,不要再连 8080 了 +URL = "ws://192.168.1.8:8084/ws" # 注意走 443,不要再连 8080 了 # 如果你的 WS 路径是 /ws/,就写成上面这样;若是别的路径自己改 def on_message(ws, msg): print("收到:", msg)