60 lines
1.5 KiB
Python
60 lines
1.5 KiB
Python
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)
|