Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 36 ยท Rooms and Namespaces

Managing Sockets from the Server

Control Socket.IO connections from the server. List sockets with fetchSockets, store socket.data, force sockets to join rooms, kick users with disconnectSockets, and choose rooms versus namespaces.

So far the server reacted to what clients asked for. Real applications also need the server to act on its own: show an admin the list of connected users, kick someone, move a group of players into a new room, or tell everybody on a plan to refresh. Socket.IO has a small set of bulk operations on any target (the whole namespace, a room, or a combination) for exactly this. This lesson covers them, and finishes with a guide for choosing between rooms and namespaces.

Selecting a target

All of the operations below work on a selection built with the broadcast operators you already know:

JavaScript
io                       // every socket in the default namespace
io.in('lobby')           // sockets in a room
io.in('a').in('b')       // union of rooms
io.in('lobby').except('muted')
io.of('/admin')          // another namespace

Then you finish the chain with one of these actions:

Method What it does
.emit(event, ...args) Send an event to the selection.
.fetchSockets() Returns a promise of socket objects matching the selection.
.socketsJoin(room) Makes every matching socket join the room(s).
.socketsLeave(room) Makes every matching socket leave the room(s).
.disconnectSockets(close?) Disconnects every matching socket (true also closes the underlying connection).
.serverSideEmit(...) (On io) sends an event to the other server processes (scaling chapter).

These methods work with a single server and, thanks to adapters, also across many servers; that is why they exist alongside direct access to local sockets.

Listing connected sockets and storing data

socket.data is an empty object per socket that is yours to fill: for example socket.data.userId or socket.data.name. It is the right place for per-connection information because fetchSockets() returns it, even for sockets on other servers. Properties you can read from the results: id, handshake, rooms, data.

Node.js A roster of connected users

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

fetchSockets returns objects that behave like sockets for reading (id, rooms, data, handshake) and for a few actions (join, leave, emit, disconnect). They are snapshots: sockets can connect or leave right after the promise resolves.

Forcing joins and kicking users

An admin action, a payment, or a matchmaker does not come from the target's own socket, so the handlers socket.join or socket.disconnect are not at hand. Use the bulk methods instead, selecting the targets by room, such as the personal room (user:<id> or the socket id):

JavaScript
// put every pro-plan socket into a "beta" room
io.in('plan:pro').socketsJoin('beta');

// a user was banned: disconnect all their sockets, on every server
io.in(`user:${userId}`).disconnectSockets();

// close even the underlying connection
io.in(`user:${userId}`).disconnectSockets(true);

Because a disconnected client with io server disconnect will not reconnect by itself, a banned user stays out until your client logic (or a manual action) retries, and your authentication middleware must refuse the banned account when it does.

Node.js Moderation: force-join and kick

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The sequence shows both halves of a proper ban: disconnect the live sockets, and refuse future connections in the middleware (a one-off kick without the second half is only a temporary inconvenience).

Rooms or namespaces?

Room Namespace
Created by the server at runtime, automatically the developer, usually at startup
Client can choose it indirectly, by asking the server directly, in the URL
Has own middleware and connection event no yes
Typical count thousands, short-lived a handful, permanent
Good for conversations, users, matches, documents areas of the app, tenants, auth boundaries
Costs one Set of ids one namespace object with its handlers

Rule of thumb: if you would think of it as an instance of something (chat #12, user #42), it is a room. If you would think of it as a kind of thing with its own rules (admin area, public chat), it is a namespace.

Start with rooms and a single namespace. Add namespaces only when you need separate middleware, separate event vocabularies or tenant isolation. Splitting too early adds connections to manage and complicates testing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which call disconnects all sockets in the room user:42?

    Selecting the room and calling disconnectSockets disconnects every matching socket, even on other servers with an adapter.
  2. 2. What is socket.data meant for?

    It is a free-form object for your own per-connection data such as user id or plan.
  3. 3. After disconnecting a banned user, what must you also do so they stay out?

    The client may reconnect, so authentication middleware must check the ban list.
  4. 4. Which is a better fit for a namespace than a room?

    Namespaces fit permanent areas with their own middleware; per-instance groups are rooms.

Summary

  • Select targets with io, in, except and of, then act with emit, fetchSockets, socketsJoin, socketsLeave or disconnectSockets.
  • Store per-connection info in socket.data; it is readable through fetchSockets.
  • Admin actions use bulk methods addressed by room, such as a personal user:<id> room.
  • A real ban disconnects live sockets and blocks new connections in middleware.
  • Rooms are for instances created at runtime; namespaces are for a few permanent areas.

Next: Middleware: Intercepting Connections