본문 바로가기
C.W.K.
Stream
Lesson 02 of 08 · published

보내기와 받기 메서드

~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_text/receive_text, 자동 직렬화되는 JSON 딕셔너리는 send_json/receive_json, 가공하지 않은 바이너리는 send_bytes/receive_bytes 를 써. receive_json() 이 JSON 을 해석하고 send_json() 이 직렬화해 주기 때문에 애플리케이션의 95% 는 이 JSON 쌍만으로 충분해.

iter_text 와 iter_json

직접 while True 반복문을 만드는 대신 async for msg in websocket.iter_json(): 같은 비동기 반복자를 쓸 수 있어. 동작은 같지만 더 간결하고, 연결이 끊기면 반복자가 멈추므로 이 형태에서는 WebSocketDisconnect 를 따로 처리할 필요가 없어.

send_json 은 메시지 형식을 정해 주지 않아

send_json(obj)json.dumps(obj) 가 만들 내용을 보낼 뿐이야. typedata 를 담는 봉투 구조까지 강제하지는 않아. 그 설계는 애플리케이션의 몫이고 트랙 5 에서 자세히 다룰 거야.

Code

엔드포인트 하나에서 여섯 메서드 사용하기·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 으로 간결하게 비동기 반복하기·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 의 에코 서버를 iter_json() 을 쓰도록 바꿔. msg['type'] 에 따라 나눠 ping 에는 pong 을 돌려주고, 나머지는 {type: 'echo', data: msg} 로 되돌려 줘. websocat 으로 JSON 을 보내 시험해.

Progress

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

댓글 0

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

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