Websocket

Handling the Notification

To process a new notification, call the function get_next_subscription_notification_by_id, passing in the subscription_id returned from the subscribe command as a parameter.

Examples

Handling the transaction notification from a Gateway Stream in Python (line 8 handles the notification):

import asyncio, json, ssl, websockets

async def main():
    try:
        ws_uri = "ws://127.0.0.1:28333/ws",
        auth_key = "YOUR_AUTHORIZATION_HEADER"

        async with websockets.connect(
            ws_uri,
            header=["Authorization:{}".format(auth_key)],
        ) as websocket:
            subscription_request = json.dumps({"id": 1, "method": "subscribe", "params": ["newTxs", {"include": ["tx_hash"]}]})
            await websocket.send(subscription_request)
            response = await websocket.recv()
            subscription_id = json.loads(response)['result']

            while True:
                response = await websocket.recv()
                response = json.loads(response)
                if response['id'] == subscription_id:
                    print(response) # or process it generally
    except Exception as e:
        print(f'Connection failed, Reason: {e}')

if __name__ == '__main__':
    asyncio.run(main())

Last updated