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

Send & Receive 메서드

~11 min · fastapi, send, receive, iter

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

세 쌍의 메서드

FastAPI 의 WebSocket 객체가 매칭된 send/receive 쌍 세 개 줘: send_text/receive_text (string), send_json/receive_json (auto-serialized JSON dict), send_bytes/receive_bytes (raw binary). receive_json() 이 parse 해주고; send_json() 이 stringify 해줘. application 의 95% 는 JSON 쌍만 써.

iter_text 와 iter_json

수동 while True loop 대신 FastAPI 가 async iterator 노출: async for msg in websocket.iter_json():. 깔끔하고 동작 같아. iterator 가 disconnect 시 멈춰 (iter form 엔 WebSocketDisconnect 처리 필요 없음).

send_json 은 format 안 정해

send_json(obj)json.dumps(obj) 가 만들 걸 보내. type/data envelope 안 강제. 그건 네 일이야 — Track 5 가 protocol 설계 다뤄.

Code

한 endpoint 에 여섯 메서드 다·python
from fastapi import FastAPI, WebSocket

app = FastAPI()

@app.websocket('/ws')
async def demo(websocket: WebSocket):
    await websocket.accept()

    # Receiving
    text  = await websocket.receive_text()       # str
    obj   = await websocket.receive_json()       # dict / list
    raw   = await websocket.receive_bytes()      # bytes

    # Sending
    await websocket.send_text('hi')
    await websocket.send_json({'type': 'hello', 'data': {'ok': True}})
    await websocket.send_bytes(b'\x00\x01\x02')

    # Closing
    await websocket.close(code=1000, reason='done')
iter_json — 깔끔한 async 반복·python
@app.websocket('/ws')
async def chat(websocket: WebSocket):
    await websocket.accept()
    async for msg in websocket.iter_json():
        # msg is already a dict
        if msg.get('type') == 'ping':
            await websocket.send_json({'type': 'pong'})
        else:
            await websocket.send_json({'type': 'echo', 'data': msg})

External links

Exercise

t3l1 의 echo 서버를 iter_json() 쓰게 변환. msg['type'] 으로 route: pingpong 리턴, 나머지는 {type: 'echo', data: msg} 로 echo. websocat 으로 JSON 보내며 테스트.

Progress

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

댓글 0

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

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