Я постоянно получаю сообщение об ошибке тайм-аута, которую сейчас не могу объяснить. Я новичок в сетевых технологиях на Python, но могу создавать примеры кода веб-сокетов и взаимодействовать с ними. По какой-то причине приведенный ниже код выдает ошибку TimeOutError каждый раз, когда я пытаюсь подключиться.
Для справки: AIS Stream — это канал данных о доставке, и я ожидаю получить ответ на всех кораблях рядом с портами Буэнос-Айреса и Сан-Франциско.
Кто-нибудь еще сталкивался с этим/кто-нибудь знает, почему это происходит?
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())```
Подробнее здесь: https://stackoverflow.com/questions/797 ... -handshake