C.W.K.
Stream
Lesson 04 of 07 · published

Rooms & Namespaces

~12 min · library, rooms, namespaces

Level 0Poller
0 XP0/60 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Rooms: server-side groups

Rooms in Socket.IO are server-side groupings, like the rooms you built in Track 4. Use sio.enter_room(sid, 'general') to add a connection to a room; sio.emit(event, data, room='general') to broadcast. Rooms are lightweight — create them on demand, do not pre-declare.

Namespaces: client-side channels

Namespaces multiplex a single underlying connection into separate logical scopes. Connect to /chat and /notifications from the same browser, share one transport, but get two independent event streams with their own rooms and handlers. Useful when one app has multiple unrelated real-time concerns.

skip_sid prevents echo

When you broadcast to a room, the sender is in that room too. Pass skip_sid=sid to omit the sender from the broadcast. This is the Socket.IO equivalent of the exclude=ws parameter you wrote in Track 4.

Code

Server-side rooms·python
@sio.on('room:join')
async def join(sid, data):
    sio.enter_room(sid, data['room'])
    sess = await sio.get_session(sid)
    await sio.emit('user:joined',
        {'user': sess['user']['name']},
        room=data['room'], skip_sid=sid)

@sio.on('chat:message')
async def message(sid, data):
    sess = await sio.get_session(sid)
    await sio.emit('chat:message', {
        'from': sess['user']['name'],
        'text': data['text'],
    }, room=data['room'], skip_sid=sid)

@sio.on('room:leave')
async def leave(sid, data):
    sio.leave_room(sid, data['room'])
Namespaces — client and server·python
# Server: separate handlers per namespace
@sio.on('connect', namespace='/chat')
async def chat_connect(sid, environ, auth):
    print('chat connect', sid)

@sio.on('connect', namespace='/notifications')
async def notif_connect(sid, environ, auth):
    print('notifications connect', sid)
Namespaces — client·javascript
import { io } from 'socket.io-client';

// Two namespaces share one underlying connection.
const chat = io('https://api.example.com/chat', { auth });
const notif = io('https://api.example.com/notifications', { auth });

chat.emit('chat:message', { text: 'hi', room: 'general' });
notif.on('alert', showToast);

External links

Exercise

Build a server with two namespaces: /chat and /notifications. Each has its own connect handler logging the sid. Connect from one browser using both namespaces; confirm in network tab that both share a single WebSocket but receive independent events.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.