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

Room & Namespace

~12 min · library, rooms, namespaces

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

Room: 서버쪽 group

Socket.IO 의 room 이 Track 4 에서 만든 room 처럼 서버쪽 grouping. sio.enter_room(sid, 'general') 로 connection 을 room 에 추가; sio.emit(event, data, room='general') 로 broadcast. Room 가벼움 — on demand 만들고 사전 declaration 안 함.

Namespace: 클라쪽 channel

Namespace 가 단일 underlying connection 을 별도 logical scope 로 multiplex. 같은 브라우저에서 /chat + /notifications connect, 한 transport 공유, 자기 room + handler 가진 두 독립 event stream 받음. 한 앱이 여러 무관한 real-time 관심사 가질 때 유용.

skip_sid 가 echo 막아

Room 에 broadcast 할 때 sender 도 그 room 에 있어. skip_sid=sid 넘기면 sender 가 broadcast 에서 빠짐. Track 4 에서 짠 exclude=ws 의 Socket.IO 등가물.

Code

서버쪽 room·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'])
Namespace — 클라와 서버·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)
Namespace — 클라·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

두 namespace (/chat, /notifications) 가진 서버 짜. 각자 sid 로그하는 connect handler. 한 브라우저에서 둘 다 namespace 사용 connect; network 탭에서 둘이 단일 WebSocket 공유하지만 독립 event 받는 거 확인.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.