diff --git a/out_service/cd.py b/out_service/cd.py index b7bc5bdd..61e1b299 100644 --- a/out_service/cd.py +++ b/out_service/cd.py @@ -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: