Skip to content

Broadcast

Gerasimos (Makis) Maropoulos edited this page Oct 26, 2026 · 10 revisions

When to use this page

  • You want to send a message to every connection on the server.
  • You want to send a message to a subset (a room, a namespace, or "every client except the sender").
  • You want to send a message to a specific connection by ID.

Neffos broadcasting is non-blocking by default: a slow client never holds up new connections or other broadcasts. This is a significant departure from naive "iterate the connection list under a lock" schemes.

The big picture

A client never talks directly to another client. All traffic goes through the server, so the server is the only broadcaster. Two layers of helpers:

API Use when
NSConn.Broadcast(...) / NSConn.BroadcastOthers(...) You are inside an event callback and have the NSConn. Most common.
Server.Broadcast(exceptSender, msgs...) You don't have an NSConn, for example in an HTTP handler that fires a notification, or in a background goroutine.

Broadcasting from inside an event callback

The recommended path. The new helpers in NSConn (Broadcast and BroadcastOthers) replace the older c.Conn.Server().Broadcast(c, msg) chain:

neffos.Events{
    "chat": func(c *neffos.NSConn, msg neffos.Message) error {
        // Echo the message to everyone EXCEPT the sender.
        c.BroadcastOthers(msg)
        return nil
    },
}

Broadcast sends to everyone including the sender; BroadcastOthers excludes the current connection. Both are server-side only: calling them on a client-side NSConn does nothing.

Broadcasting from outside an event (Server.Broadcast)

When you don't have an NSConn (background job, HTTP handler, signal handler), use Server.Broadcast:

// websocketServer := neffos.New(...)

websocketServer.Broadcast(nil, neffos.Message{
    Namespace: "default",
    Event:     "system.notice",
    Body:      []byte("scheduled maintenance in 5 minutes"),
})

The first parameter is the exceptSender, a neffos.Sender. Pass nil to broadcast to everyone, or one of the four values that implement it (the interface is sealed, you cannot add a fifth):

  • *neffos.Conn (the sender's connection)
  • *neffos.NSConn (the sender's namespaced connection)
  • *neffos.Room (the connection that joined the room; the room's other members still receive the message)
  • neffos.Exclude("connection-id") if you only have the string ID

All four work the same under a Scale out StackExchange: the exclusion travels with the message through redis or nats, so the sender does not get its own broadcast back from another node either. Exclude resolves the ID against the connections of the server you call it on; an ID that belongs to a connection on another node is excluded on this node only. (Before v0.0.25, Exclude and *Room were silently ignored whenever a StackExchange was configured.)

Targeting a specific connection (Message.To)

To send a message to one connection by ID, fill Message.To:

websocketServer.Broadcast(nil, neffos.Message{
    Namespace: "default",
    Event:     "notification",
    Body:      []byte("you've got mail"),
    To:        "user-42",
})

The Namespace and Room checks still apply: the target connection must be connected to the namespace (and joined to the room, if Room is set).

Targeting a room

Fill Message.Room to deliver to every connection joined to that room within the namespace:

websocketServer.Broadcast(nil, neffos.Message{
    Namespace: "default",
    Room:      "lobby",
    Event:     "chat",
    Body:      []byte("welcome!"),
})

When called from an event callback, the NSConn helpers stay shorter:

c.BroadcastOthers(neffos.Message{
    Room:  "lobby",
    Event: "chat",
    Body:  []byte("welcome!"),
})

(Namespace is filled automatically from the NSConn.)

Delivery semantics

  • No dropped messages, but backpressure instead. The broadcaster never discards a message for a connection that is still open: a slow connection's pending broadcasts queue up in memory until its writer catches up. A connection that never catches up is eventually closed by its write deadline or the heartbeat (see Timeouts), not by the broadcaster giving up on it. There is still no per-message ack; if you need delivery confirmation, use The ask method instead.
  • Non-blocking. Server.Broadcast returns immediately. Slow consumers never block accepts or other broadcasts.
  • Order is per-receiver, not global. Two Broadcast calls A then B will each arrive at each receiver in order A to B, but two receivers may see them at different times.
  • Emit returns a bool, Send returns an error. NSConn.Emit/EmitBinary and Room.Emit keep their old bool result: false just means the write did not happen (closed connection, wrong namespace, wrong room). Conn.Send, NSConn.Send and Room.Send do the same write but return an error instead, so you can tell ErrBadNamespace apart from ErrBadRoom or a closed connection (errors.Is(err, ErrWrite)) instead of just getting false. Use Send wherever you want to branch on why a broadcast did not go out.

Ordering trade-off: Server.SyncBroadcaster

If you need strict ordering at the cost of throughput (no in-flight overlap), set Server.SyncBroadcaster = true before clients connect:

ws := neffos.New(upgrader, handler)
ws.SyncBroadcaster = true

When a StackExchange is configured (Redis / NATS) this flag is ignored, since the backend already serializes order.

Running code on every connection (Server.Do)

Broadcast only sends messages. To run arbitrary code on every connection (close them, increment counters, gather state), use Server.Do:

// Count how many connections are in the "default" namespace.
var inDefault int
websocketServer.Do(func(c *neffos.Conn) {
    if c.Namespace("default") != nil {
        inDefault++
    }
}, false)

log.Printf("%d of %d connections are in \"default\"", inDefault, websocketServer.GetTotalConnections())

Server.GetTotalConnections() is an atomic read and cheap. Conn.Namespace(name) returns nil, not a dangling value, when the connection never joined that namespace, so check it before calling anything on the result.

Or to terminate every connection entirely:

websocketServer.Do(func(c *neffos.Conn) {
    c.Close()
}, false)

Important: Server.Do runs on the server's dispatch goroutine. New connections keep being accepted while fn runs (registering one takes its own lock, not the dispatch loop), but long work inside fn still delays other Do calls, disconnect notifications and synchronous broadcasts until it returns. Keep fn non-blocking: counting, reading or writing local state, and the odd Conn.Close()/Terminate() are fine; a call that waits for a reply from the remote side, such as NSConn.Disconnect, is not (see Connections). Pass async = true if you need fire-and-forget.

See also

Clone this wiki locally