I keep getting a timeout error which I can't currently explain. I'm new to networking in Python, but I can create and interact with example websocket code. For some reason the code below hits a TimeOutError every time I try to connect.
For reference AIS Stream is a shipping data feed, and I'm expecting to get a response on all ships near the Buenos Aires and San Fran ports.
Has anyone else experienced this/ does anyone know why this is happening?
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:
Trying to connect to WebSocket...
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 <module>
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