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

첫 WebSocket Endpoint

~12 min · fastapi, server, accept

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

일곱 줄짜리 서버

FastAPI 가 WebSocket 을 @app.websocket decorator 로 노출. handler 는 WebSocket 인자 하나 받는 coroutine. 세 가지가 순서대로 일어나야 해: await websocket.accept() 로 handshake 완료, await websocket.receive_*() loop 안에서, await websocket.send_*() 로 응답.

accept() 는 옵션 아냐

accept() 부르기 전엔 handshake 미완료, 모든 send 가 throw. accept 안 하기 도 선택지야 — auth 체크 중 connection reject 하는 방법이 그거. accept 후엔 connection 완전 열림, frame 흘러.

실행 & 테스트

uvicorn 으로 띄우고; CLI 에서 websocat 이나 wscat 로 테스트. cwkPippa 는 의도적으로 --reload 없이 Uvicorn 돌려 (피파 adapter 가 살아있는 brain stem; reload 가 session 죽여). 학습 땐 --reload 써.

Code

일곱 줄짜리 echo 서버·python
from fastapi import FastAPI, WebSocket

app = FastAPI()

@app.websocket('/ws')
async def echo(websocket: WebSocket):
    await websocket.accept()
    while True:
        text = await websocket.receive_text()
        await websocket.send_text(f'echo: {text}')
실행 & 테스트·shell
pip install 'fastapi[standard]' uvicorn

# Run
uvicorn main:app --reload --host 0.0.0.0 --port 8000

# Test from a second terminal
brew install websocat   # or: cargo install websocat
websocat ws://localhost:8000/ws
> hello
echo: hello

External links

Exercise

Echo 서버 짜. 브라우저 탭에서 new WebSocket('ws://localhost:8000/ws') 열고 message 세 개 보내고 echo 확인. 그 다음 await websocket.accept() 주석 처리하고 무슨 일 일어나는지 봐 — 서버가 로그하는 정확한 에러 메시지 적어.

Progress

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

댓글 0

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

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