feat: 优化cd.py

This commit is contained in:
caoqianming 2025-09-16 18:51:38 +08:00
parent 70cdf0d1c6
commit 2c9c74131c
1 changed files with 33 additions and 37 deletions

View File

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