{"record":{"id":"afb5cafe5afe6604","repo":"iflytek/astron-agent","slug":"websocketclientnotconnectederror","errorCode":"WebSocketClientNotConnectedError","errorMessage":"{e}","messagePattern":"\\{e\\}","errorType":"error_code","errorClass":"WebSocketClientException","httpStatus":null,"severity":"error","filePath":"core/plugin/aitools/common/clients/websockets_client.py","lineNumber":100,"sourceCode":"                )\n\n                if new_url is None:\n                    log.error(\"WebSocket auth failed\")\n                    raise WebSocketClientException.from_error_code(\n                        CodeEnums.WebSocketClientAuthError, extra_message=\"ASE 鉴权失败\"\n                    )\n\n                self.url = new_url\n        except Exception:\n            raise\n\n    async def connect(self) -> None:\n        \"\"\"Connect to WebSocket server\"\"\"\n        try:\n            self.ws = await websockets.connect(self.url, **self.ws_params)\n            self._running = True\n        except Exception as e:\n            raise WebSocketClientException.from_error_code(\n                CodeEnums.WebSocketClientNotConnectedError, extra_message=str(e)\n            )\n\n        self._tasks.append(self.task_factory.create(self._send_loop()))\n        self._tasks.append(self.task_factory.create(self._recv_loop()))\n\n    async def send(self, data: Any) -> None:\n        \"\"\"Send data to WebSocket server\"\"\"\n        self.send_data_list.append(data)\n        if not self._running:\n            raise WebSocketClientException.from_error_code(\n                CodeEnums.WebSocketClientNotConnectedError,\n                extra_message=\"WebSocket 未连接\",\n            )\n        else:\n            if isinstance(data, str) or isinstance(data, bytes):\n                await self.send_queue.put(data)\n            elif isinstance(data, dict) or isinstance(data, list):","sourceCodeStart":82,"sourceCodeEnd":118,"githubUrl":"https://github.com/iflytek/astron-agent/blob/5e758547a83371a5a4b29dadf4ac03e8dd527635/core/plugin/aitools/common/clients/websockets_client.py#L82-L118","documentation":"WebSocketClientNotConnectedError is raised by WebSocketClient.connect when the initial websockets.connect() handshake to the server fails for any reason (DNS, TLS, refused connection, invalid URL). The client wraps the raw exception and preserves its message via extra_message. No send/recv loops are started when this fires.","triggerScenarios":"Calling await client.connect() (typically via start()) when the WebSocket server is down, the URL is wrong, TLS certs fail, auth query params are rejected, or the network is unreachable — any exception from websockets.connect().","commonSituations":"Misconfigured ws:// vs wss:// URL, service not started yet in docker-compose, wrong port or missing API key in ws_params, firewall/proxy blocking the upgrade request, expired credentials causing server to reject the handshake.","solutions":["Verify the WebSocket URL is reachable (curl the HTTP upgrade endpoint or ping the host/port).","Check self.ws_params for correct auth credentials, headers, and ssl context.","Ensure the target service is running and the port is exposed (docker-compose / k8s service).","Confirm network egress (proxy, firewall) allows WebSocket upgrades to the host."],"exampleFix":"// before\nclient = WebSocketClient(\"wss://api.example.com/ws\", ws_params={})\nawait client.connect()\n\n// after\nclient = WebSocketClient(\"wss://api.example.com/ws\", ws_params={\"extra_headers\": {\"Authorization\": f\"Bearer {token}\"}})\ntry:\n    await client.connect()\nexcept WebSocketClientException as e:\n    logger.error(f\"WS connect failed: {e}\")\n    raise","handlingStrategy":"try-catch","validationCode":"from urllib.parse import urlparse\nimport socket\ndef can_reach_ws(url: str) -> bool:\n    p = urlparse(url)\n    try:\n        socket.create_connection((p.hostname, p.port or (443 if p.scheme == 'wss' else 80)), timeout=5).close()\n        return True\n    except OSError:\n        return False","typeGuard":"def is_ws_url(url: str) -> bool:\n    return url.startswith(('ws://', 'wss://'))","tryCatchPattern":"try:\n    await client.connect()\nexcept WebSocketClientException as e:\n    logger.error(f\"ws connect failed: {e}\")\n    await schedule_reconnect(client)","preventionTips":["Health-check the WS endpoint before connect","Keep credentials in ws_params fresh and validated","Use wss:// with valid certs in production","Add exponential-backoff reconnect on failure"],"tags":["websocket","connection","network"],"backgroundTag":"connection-refused","analyzedSha":"5e758547a83371a5a4b29dadf4ac03e8dd527635","analyzedAt":"2026-09-12T08:03:51.356Z","contentChangedAt":"2026-09-12T08:03:51.356Z","schemaVersion":2},"datasetVersion":"2026-09-15T23:17:13.987Z"}