This commit is contained in:
caoqianming 2025-09-17 11:15:17 +08:00
commit f60250bb21
1 changed files with 33 additions and 37 deletions

View File

@ -75,46 +75,42 @@ class JSONRequestHandler(BaseHTTPRequestHandler):
with sc_lock: # 加锁,防止竞争 with sc_lock: # 加锁,防止竞争
sc = sc_all[addr] sc = sc_all[addr]
try: try:
if sc is None: if sc is None:
sc = socket.socket() sc = socket.socket()
sc.settimeout(5) sc.settimeout(5)
sc.connect((host, int(port))) sc.connect((host, int(port)))
with sc_lock: # 再次加锁,更新 sc_all
sc_all[addr] = sc sc_all[addr] = sc
sc.settimeout(0.5)
sc.settimeout(0.5) while True:
while True: try:
try: data = sc.recv(65536)
data = sc.recv(65536) if not data:
if not data: break
except (socket.timeout, BlockingIOError):
break break
except (socket.timeout, BlockingIOError):
break
sc.settimeout(5) sc.settimeout(5)
sc.sendall(b"R") sc.sendall(b"R")
data = bytearray() data = bytearray()
while len(data) < 8: while len(data) < 8:
chunk = sc.recv(1024) chunk = sc.recv(1024)
if not chunk: if not chunk:
raise ConnectionError("连接中断") raise ConnectionError("连接中断")
data.extend(chunk) data.extend(chunk)
return sc, bytes(data) return sc, bytes(data)
except Exception as e: except Exception as e:
if sc is not None: if sc is not None:
try: try:
sc.close() sc.close()
except Exception: except Exception:
pass pass
with sc_lock: # 加锁,清除无效连接
sc_all[addr] = None sc_all[addr] = None
self.error(f'采集器通信失败: {e}') self.error(f'采集器通信失败: {e}')
print(traceback.format_exc()) return None, None
return None, None
sc, resp = connect_and_send() sc, resp = connect_and_send()
if sc is None or resp is None: if sc is None or resp is None: