본문 바로가기
C.W.K.
Stream
Lesson 04 of 07 · published

방과 네임스페이스

~12 min · library, rooms, namespaces

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

방: 서버 쪽 연결 묶음

Socket.IO 의 방은 트랙 4 에서 만든 방과 같은 서버 쪽 묶음이야. sio.enter_room(sid, 'general') 로 연결을 방에 넣고 sio.emit(event, data, room='general') 로 모두에게 보내. 방은 가벼워서 필요할 때 만들고 미리 선언할 필요가 없어.

네임스페이스: 클라이언트 쪽 채널

네임스페이스는 물리 연결 하나를 여러 논리 영역으로 나눠 함께 전달해. 같은 브라우저에서 /chat/notifications 에 연결하면 전송 수단 하나를 공유하면서 각자 방과 처리기를 가진 독립 이벤트 흐름 둘을 받아. 한 앱에 서로 무관한 실시간 관심사가 여러 개 있을 때 유용해.

skip_sid 로 발신자 되돌림 막기

방 전체에 보낼 때 발신자도 그 방의 구성원이야. skip_sid=sid 를 넘기면 발신자를 제외할 수 있어. 트랙 4 에서 만든 exclude=ws 와 같은 Socket.IO 기능이야.

Code

서버 쪽 방·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'])
네임스페이스 — 클라이언트와 서버·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)
네임스페이스 — 클라이언트·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

/chat/notifications 네임스페이스를 가진 서버를 만들고 각각 연결할 때 sid 를 기록해. 한 브라우저에서 둘 모두에 연결한 뒤 네트워크 탭에서 WebSocket 하나를 공유하면서도 독립된 이벤트를 받는지 확인해.

Progress

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

댓글 0

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

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