Python - websocket.send()

Send a message to a connected websocket client.

from nitric.resources import websocket
from nitric.application import Nitric

public_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

Examples

Broadcast messages to all connected clients

from nitric.resources import api, websocket, collection
from nitric.application import Nitric
from nitric.context import WebsocketContext

connections = 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()