Go - Websocket.Send()

Send a message from the websocket to a connection.

import (
"context"
"github.com/nitrictech/go-sdk/nitric"
)
func main() {
ws := nitric.NewWebsocket("public")
ws.Send(context.TODO(), "D28BA458-BFF4-404A", []byte("Hello World"))
nitric.Run()
}

Parameters

  • Name
    ctx
    Required
    Required
    Type
    context
    Description

    The context of the call, used for tracing.

  • Name
    connectionId
    Required
    Required
    Type
    string
    Description

    The ID of the connection which should receive the message.

  • Name
    message
    Required
    Required
    Type
    []byte
    Description

    The message that should be sent to the connection.

Examples

Broadcasting a message to all connections.

Do not send messages to a connection during it's connect callback, if you need to acknowledge connection, do so by using a topic

import (
"context"
"github.com/nitrictech/go-sdk/nitric"
"github.com/nitrictech/go-sdk/nitric/keyvalue"
"github.com/nitrictech/go-sdk/nitric/websockets"
)
func main() {
ws := nitric.NewWebsocket("public")
connections := nitric.NewKv("connections").Allow(keyvalue.KvStoreGet, keyvalue.KvStoreSet, keyvalue.KvStoreDelete)
// Register a new connection on connect
ws.On(websockets.EventType_Connect, func(ctx *websockets.Ctx) error {
return connections.Set(context.TODO(), ctx.Request.ConnectionID(), map[string]interface{}{
"connectionId": ctx.Request.ConnectionID(),
})
})
// Remove a registered connection on disconnect
ws.On(websockets.EventType_Disconnect, func(ctx *websockets.Ctx) error {
return connections.Delete(context.TODO(), ctx.Request.ConnectionID())
})
// Broadcast message to all the registered websocket connections
ws.On(websockets.EventType_Message, func(ctx *websockets.Ctx) error {
connectionStream, err := connections.Keys(context.TODO())
if err != nil {
return err
}
for {
connectionId, err := connectionStream.Recv()
if err != nil {
break // reached the end of the documents
}
err = ws.Send(context.TODO(), connectionId, []byte(ctx.Request.Message()))
if err != nil {
return err
}
}
return nil
})
nitric.Run()
}
Last updated on Oct 15, 2024