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

Socket.IO 서버 (Python)

~12 min · library, python-socketio, fastapi

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

python-socketio + FastAPI

표준 Python Socket.IO 서버는 python-socketio. asgi 지원, FastAPI 통합, horizontal scaling 위한 Redis manager 동봉. 패턴: REST endpoint 위해 FastAPI 앱 만들고, AsyncServer 로 Socket.IO 서버 만들고, 둘 다 ASGIApp 로 wrap, uvicorn 이 통째로 serve.

connect 의 auth

Socket.IO 의 connect handler 가 auth dict 를 query string 과 헤더와 별개로 받음 — 클라가 SDK 의 auth 옵션으로 넘겨. validate; invalid 면 ConnectionRefusedError raise, 클라가 connection 성공한 거 아예 못 봄. user identity 를 sio.save_session(sid, ...) 에 저장해서 다음 handler 에 사용.

Code

FastAPI + Socket.IO 서버·python
import socketio
from fastapi import FastAPI

# REST app
api = FastAPI()

@api.get('/health')
async def health():
    return {'ok': True}

# Socket.IO server
sio = socketio.AsyncServer(async_mode='asgi', cors_allowed_origins='*')

@sio.event
async def connect(sid, environ, auth):
    token = (auth or {}).get('token')
    if not token or not validate_token(token):
        raise socketio.exceptions.ConnectionRefusedError('unauthorized')
    user = decode(token)
    await sio.save_session(sid, {'user': user})
    print('connected', sid, user['name'])

@sio.event
async def disconnect(sid):
    print('disconnected', sid)

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

# Mount everything together
app = socketio.ASGIApp(sio, other_asgi_app=api)
# Run: uvicorn main:app --host 0.0.0.0 --port 8000

External links

Exercise

위 서버 짜. valid token 으로 Socket.IO 클라 connect, 그 다음 invalid 로. valid 가 성공, 나쁜 거가 클라쪽 connect_error 표시 확인. 클라쪽 SDK 없으면 connect 자체 안 됨 — 그것도 확인.

Progress

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

댓글 0

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

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