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.
After subscribing to a stream, your application receives a notification for each published event (for example, a new transaction or block). This section explains how to handle stream notifications using the supported protocols: WebSocket and gRPC. Both approaches are covered below.
WebSocket
For WebSocket subscriptions, notifications are delivered over the established WebSocket connection. Each notification includes the subscription_id returned by the initial subscribe call.
To process a notification, listen for incoming messages and match the message id with the corresponding subscription_id.
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())Handling the transaction notification from a Cloud-API Stream in Python (version 3.7 or higher):
Handling the transaction notification from a Cloud-API Stream in Python (version 3.7 or higher):
gRPC
For gRPC subscriptions, notifications are received by calling Recv() on the stream object returned by the subscription request. Each call to Recv() blocks until a new event is available or an error occurs.
Example
Subscribing to Gateway Stream in Go using gRPC (ex: NewTxs stream):
Last updated