Python - websocket.send()
Send a message to a connected websocket client.
from nitric.resources import websocketfrom nitric.application import Nitricpublic_websocket = websocket("public")async def send_hello_message(connection_id: string):await public_websocket.send(connection_id, b"Hello")Nitric.run()
Parameters
- Name
connection_id
- Required
- Required
- Type
- string
- Description
The ID of the connection to send the message to on this websocket.
- Name
data
- Required
- Required
- Type
- bytes
- Description
The byte data to send to that connection
Do not send messages to a connection during it's connect
callback, if you
need to acknowledge connection, do so by using a topic
Examples
Broadcast messages to all connected clients
from nitric.resources import api, websocket, collectionfrom nitric.application import Nitricfrom nitric.context import WebsocketContextconnections = collection("connections").allow("reading", "writing", "deleting")main_websocket = websocket("main")@main_websocket.on("connect")async def connect(ctx: WebsocketContext):await connections.doc(ctx.req.connection_id).set({})@main_websocket.on("disconnect")async def disconnect(ctx: WebsocketContext):await connections.doc(ctx.req.connection_id).delete()@main_websocket.on("message")async def message(ctx: WebsocketContext):all = connections.query().stream()async for conn in all:await main_websocket.send(conn.id, ctx.req.data)Nitric.run()
Last updated on Jan 14, 2025