Python Asyncio: Zeitüberschreitung beim öffnenden HandshakePython

Python-Programme
Anonymous
 Python Asyncio: Zeitüberschreitung beim öffnenden Handshake

Post by Anonymous »

Ich erhalte ständig einen Timeout-Fehler, den ich derzeit nicht erklären kann. Ich bin neu im Networking in Python, kann aber Beispiel-Websocket-Code erstellen und damit interagieren. Aus irgendeinem Grund stößt der folgende Code jedes Mal auf einen TimeOutError, wenn ich versuche, eine Verbindung herzustellen.
Zur Referenz: AIS Stream ist ein Schifffahrtsdaten-Feed, und ich erwarte eine Antwort von allen Schiffen in der Nähe der Häfen von Buenos Aires und San Francisco.
Hat das noch jemand erlebt/weiß jemand, warum das passiert?

Code: Select all

import asyncio
import websockets
import json
from datetime import datetime, timezone

async def connect_ais_stream():
try:
print("Trying to connect to WebSocket...")
async with websockets.connect("wss://stream.aisstream.io/v0/stream") as websocket:
print("Connected to WebSocket.")

subscribe_message = {
"APIKey": "KEY",  # ← My API key is here and valid
"BoundingBoxes": [
# Buenos Aires, Argentina
[[-34.811548, -58.537903], [-34.284453, -57.749634]],
# San Francisco, USA
[[36.989391, -123.832397], [38.449287, -121.744995]],
],
"FilterMessageTypes": ["PositionReport"]
}

await websocket.send(json.dumps(subscribe_message))
print("Subscription message sent.")

while True:
try:
print("Waiting for message...")
message_json = await asyncio.wait_for(websocket.recv(), timeout=30)
print("Message received.")
message = json.loads(message_json)

if "MessageType"  in message:
if message["MessageType"] == "PositionReport":
report = message.get("Message", {}).get("PositionReport", {})
print(f"[{datetime.now(timezone.utc)}] ShipId: {report.get('UserID')} "
f"Latitude: {report.get('Latitude')} Longitude: {report.get('Longitude')}")
else:
print("MessageType key not found.")
except asyncio.TimeoutError:
print("No messages received in the last 30 seconds.")
except json.JSONDecodeError as e:
print(f"JSON decode error: {e}")
except websockets.ConnectionClosed as e:
print(f"Connection closed: {e}")
except Exception as e:
print(f"Error: {e}")

if __name__ == "__main__":
asyncio.run(connect_ais_stream())```

The traceback:
Es wird versucht, eine Verbindung zu WebSocket herzustellen...

Code: Select all

Trying to connect to WebSocket...
Traceback (most recent call last):
File "C:\Users\GDKYCH\Jupyter\AISStream_PoC\venv\Lib\site-packages\websockets\asyncio\client.py", line 541, in __await_impl__
self.connection = await self.create_connection()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\GDKYCH\Jupyter\AISStream_PoC\venv\Lib\site-packages\websockets\asyncio\client.py", line 467, in create_connection
_, connection = await loop.create_connection(factory, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\Python313\Lib\asyncio\base_events.py", line 1136, in create_connection
sock = await self._connect_sock(
^^^^^^^^^^^^^^^^^^^^^^^^^
exceptions, addrinfo, laddr_infos)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\Python313\Lib\asyncio\base_events.py", line 1039, in _connect_sock
await self.sock_connect(sock, address)
File "C:\Program Files\Python313\Lib\asyncio\proactor_events.py", line 726, in sock_connect
return await self._proactor.connect(sock, address)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
asyncio.exceptions.CancelledError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\Users\GDKYCH\Jupyter\AISStream_PoC\venv\Lib\site-packages\websockets\asyncio\client.py", line 539, in __await_impl__
async with asyncio_timeout(self.open_timeout):
~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\Python313\Lib\asyncio\timeouts.py", line 116, in __aexit__
raise TimeoutError from exc_val
TimeoutError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\Users\GDKYCH\Jupyter\AISStream_PoC\client.py", line 50, in 
asyncio.run(connect_ais_stream())
~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\Python313\Lib\asyncio\runners.py", line 194, in run
return runner.run(main)
~~~~~~~~~~^^^^^^
File "C:\Program Files\Python313\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^
File "C:\Program Files\Python313\Lib\asyncio\base_events.py", line 720, in run_until_complete
return future.result()
~~~~~~~~~~~~~^^
File "C:\Users\GDKYCH\Jupyter\AISStream_PoC\client.py", line 9, in connect_ais_stream
async with websockets.connect("wss://stream.aisstream.io/v0/stream", ping_timeout=10000) as websocket:
~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\GDKYCH\Jupyter\AISStream_PoC\venv\Lib\site-packages\websockets\asyncio\client.py", line 587, in __aenter__
return await self
^^^^^^^^^^
File "C:\Users\GDKYCH\Jupyter\AISStream_PoC\venv\Lib\site-packages\websockets\asyncio\client.py", line 578, in __await_impl__
raise TimeoutError("timed out during opening handshake") from exc
TimeoutError: timed out during opening handshake

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post