Node.js - websocket.send()

Send a message to a connected websocket client.

import { websocket } from '@nitric/sdk'

const socket = websocket('socket')

/**
 * Send a message to a connected client.
 *
 * @param connectionId the client received when connecting to the websocket
 * @param message to send to the client
 */
const sendMessage = async (connectionId, message) => {
  await socket.send(connectionId, message)
}

Parameters

  • Name
    connectionId
    Required
    Required
    Type
    string
    Description

    The ID of the connection which should receive the message.

  • Name
    message
    Required
    Required
    Type
    string | Uint8Array | Record<string, any>
    Description

    The message that should be sent to the connection.

Examples

Broadcasting a message to all connections.

import { websocket, kv } from '@nitric/sdk'

const socket = websocket('socket')
const connections = kv('connections').allow('get', 'set', 'delete')

socket.on('connect', async (ctx) => {
  let conns = {}
  try {
    conns = await connections.get('connections')
  } catch (e) {
    console.log('creating new connections store')
  }
  await connections.set('connections', {
    ...conns,
    [ctx.req.connectionId]: new Date(),
  })
})

socket.on('disconnect', async (ctx) => {
  const conns = await connections.get('connections')
  delete conns[ctx.req.connectionId]
  await connections.set('connections', conns)
})

const broadcast = async (data) => {
  const conns = await connections.get('connections')

  await Promise.all(
    Object.keys(conns).map(async (connectionId) => {
      // Send message to a connection
      await socket.send(connectionId, data)
    })
  )
}

socket.on('message', async (ctx) => {
  // broadcast message to all clients (including the sender)
  await broadcast(ctx.req.data)
})