Repository navigation
Broadcast
- 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.
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. |
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.
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.)
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).
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.)
- 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.Broadcastreturns immediately. Slow consumers never block accepts or other broadcasts. -
Order is per-receiver, not global. Two
Broadcastcalls A then B will each arrive at each receiver in order A to B, but two receivers may see them at different times. -
Emitreturns a bool,Sendreturns an error.NSConn.Emit/EmitBinaryandRoom.Emitkeep their oldboolresult:falsejust means the write did not happen (closed connection, wrong namespace, wrong room).Conn.Send,NSConn.SendandRoom.Senddo the same write but return anerrorinstead, so you can tellErrBadNamespaceapart fromErrBadRoomor a closed connection (errors.Is(err, ErrWrite)) instead of just gettingfalse. UseSendwherever you want to branch on why a broadcast did not go out.
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 = trueWhen a StackExchange is configured (Redis / NATS) this flag is ignored, since the backend already serializes order.
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)returnsnil, 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.
- Namespaces and Rooms, to scope your broadcasts
- The ask method, when you need a reply
- Scale out, broadcasting across multiple neffos instances
Home | About | Project | Getting Started | Technical Docs | Copyright © 2019-2026 Gerasimos Maropoulos. Documentation terms of use.
Getting started
Concepts
Messaging
Production
Scale out