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

Disconnection 처리

~11 min · fastapi, disconnect, cleanup

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

WebSocketDisconnect 가 신호

클라가 close — clean 이든 abrupt 든 — 다음 receive_* 호출이 WebSocketDisconnect raise. 예외에 .code (close code) 와 .reason (close frame reason) 들어있어. session 끝났다는 단일 권위 신호.

Cleanup 은 except 블록에

connect 에서 set up 한 모든 거 (connection manager 에 추가, heartbeat task 등록, DB row 열기) 여기서 tear down. 패턴은 connect → register → try/loop/except → unregister. unregister 건너뛰지 마; orphan reference 가 WebSocket 서버가 scale 에서 메모리 leak 하는 방식.

다른 예외도 일어나

message handler 의 application 버그가 자기 예외 던져. 별도로 catch 해서 클라한테 structured error 돌려주고 깔끔히 close.

Code

Connect/cleanup 전체 패턴·python
from fastapi import WebSocket, WebSocketDisconnect

@app.websocket('/ws')
async def chat(websocket: WebSocket):
    await websocket.accept()
    user_id = await register(websocket)  # your manager
    try:
        async for msg in websocket.iter_json():
            await handle(websocket, user_id, msg)
    except WebSocketDisconnect as e:
        log.info('client gone: code=%s reason=%s', e.code, e.reason)
    except Exception as e:
        log.exception('handler error')
        try:
            await websocket.close(code=1011, reason='internal error')
        except Exception:
            pass  # already closed
    finally:
        await unregister(user_id)
e.code 읽고 반응·python
except WebSocketDisconnect as e:
    if e.code == 1000:
        log.info('clean close')
    elif e.code == 1001:
        log.info('client navigated away')
    elif e.code == 1006:
        log.warning('abnormal close — laptop lid or NAT timeout, probably')
    else:
        log.warning('disconnect %s: %s', e.code, e.reason)

External links

Exercise

Echo 서버 수정해서 connect/disconnect 마다 카운터 (active connections: N) 로그. 테스트 클라 force-quit, 프로세스 kill, 깔끔히 close — 세 케이스 다 카운터가 0 으로 돌아오는지 봐. 안 돌아오면 finally 가 잘못된 거.

Progress

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

댓글 0

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

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