Skip to content

How to Cancel/Stop the Websocket in the Python Example #19

@HalukaMB

Description

@HalukaMB

Hello everyone,

first and foremost thanks for creating this endpoint and the examples in various programming languages. Unfortunately, I am a bit lost with the use and implementation of asyncio and Websockets. I have tried to implement a simple counter that should end the stream once a certain number of replies has come back from the API. However, I fail to get there.

I rewrote the function as:

async def connect_ais_stream():
    counter=0
    async with websockets.connect("wss://stream.aisstream.io/v0/stream") as websocket:

        subscribe_message = {"APIKey": aisKey, "BoundingBoxes": [[[-11, 178], [30, 74]]]}

        subscribe_message_json = json.dumps(subscribe_message)
  
        await websocket.send(subscribe_message_json)

        async for message_json in websocket:
            if counter<10:
                message = json.loads(message_json)    
                message_type = message["MessageType"]
    
                if message_type == "PositionReport":
                    # the message parameter contains a key of the message type which contains the message itself
                    counter+=1
                    
                    print(counter)
                    ais_message = message['Message']['PositionReport']
                    print(f"[{datetime.now(timezone.utc)}] ShipId: {ais_message['UserID']} Latitude: {ais_message['Latitude']} Longitude: {ais_message['Longitude']}")
            else:
                websocket.cancel()

I have the feeling that I am fundamentally misunderstanding how the async operation is run here. Could someone please help me out a little. Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions