0Pricing
FastAPI Backend Development Bootcamp · 강의

실시간 통신을 위한 WebSockets

WebSockets를 사용해 FastAPI에서 실시간 기능을 구축합니다. 연결을 수락하고 메시지를 주고받으며 여러 클라이언트에 브로드캐스트하고 비동기 패턴으로 연결 해제를 깔끔하게 처리합니다.

실시간 통신을 위한 WebSockets은(는) CoddyKit의 무료 FastAPI Backend Development Bootcamp 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 FastAPI Backend Development Bootcamp 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

From Request/Response to Real-Time

Regular HTTP is request/response: the client asks, the server answers, the connection closes. WebSockets keep a single connection open for full-duplex, real-time messaging. Perfect for chat, live dashboards, and notifications.

Why Async Fits WebSockets

A WebSocket connection lives a long time and is mostly idle waiting for messages. FastAPI's async model lets one worker handle thousands of concurrent connections without blocking.

A Minimal WebSocket Endpoint

Declare a @app.websocket route. Accept the connection, then loop receiving and sending messages.

from fastapi import FastAPI, WebSocket

app = FastAPI()

@app.websocket('/ws')
async def ws(websocket: WebSocket):
    await websocket.accept()
    while True:
        msg = await websocket.receive_text()
        await websocket.send_text(f'echo: {msg}')

Sending JSON

You can exchange structured data with receive_json and send_json instead of raw text.

data = await websocket.receive_json()
await websocket.send_json({'received': data, 'status': 'ok'})

Handling Disconnects

Clients drop off. Catch WebSocketDisconnect to clean up resources instead of crashing the handler.

from fastapi import WebSocketDisconnect

try:
    while True:
        await websocket.receive_text()
except WebSocketDisconnect:
    print('client left')

A Connection Manager

To broadcast, track active connections in a manager class. Add on connect, remove on disconnect.

class Manager:
    def __init__(self):
        self.active = []
    async def connect(self, ws):
        await ws.accept()
        self.active.append(ws)
    def disconnect(self, ws):
        self.active.remove(ws)

Broadcasting to Everyone

Loop the active connections and send each one the message. This is the core of a chat room.

async def broadcast(self, message):
    for connection in self.active:
        await connection.send_text(message)

Broadcast Logic in Plain Python

The manager is just list bookkeeping. Here is the connect/disconnect/broadcast flow simulated synchronously.

active = []
def connect(c): active.append(c)
def disconnect(c): active.remove(c)
def broadcast(msg): return [f'{c}<-{msg}' for c in active]
connect('alice'); connect('bob')
print(broadcast('hi'))
disconnect('alice')
print(broadcast('bye'))

A Chat Room Endpoint

Combine the pieces: connect, broadcast each received message, and disconnect on drop.

manager = Manager()

@app.websocket('/chat')
async def chat(ws: WebSocket):
    await manager.connect(ws)
    try:
        while True:
            text = await ws.receive_text()
            await manager.broadcast(text)
    except WebSocketDisconnect:
        manager.disconnect(ws)

Scaling Beyond One Process

An in-memory manager only knows connections on its worker. To broadcast across multiple workers or servers, use a pub/sub backend like Redis to fan out messages.

Security and Limits

Protect WebSocket endpoints:

  • Authenticate during the handshake (e.g. token in query or header).
  • Validate and size-limit incoming messages.
  • Heartbeat/ping to detect dead connections.

Quick Check

Why does an in-memory connection manager fail to broadcast correctly when you run several Uvicorn workers?

Recap

You added real-time communication:

  • Accepted WebSocket connections and exchanged text/JSON.
  • Handled WebSocketDisconnect cleanly.
  • Built a connection manager to broadcast to many clients.
  • Learned to scale with Redis pub/sub and to secure connections.

자주 묻는 질문

“실시간 통신을 위한 WebSockets” 강의는 무료인가요?

네 — “실시간 통신을 위한 WebSockets” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 FastAPI Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

“실시간 통신을 위한 WebSockets”에서 뭘 배우나요?

WebSockets를 사용해 FastAPI에서 실시간 기능을 구축합니다. 연결을 수락하고 메시지를 주고받으며 여러 클라이언트에 브로드캐스트하고 비동기 패턴으로 연결 해제를 깔끔하게 처리합니다. 브라우저에서 직접 실행하는 실습 코드로 FastAPI Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

FastAPI Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 FastAPI Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.

“실시간 통신을 위한 WebSockets” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 FastAPI Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 FastAPI Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Python 비동기 프로그래밍 복습
  2. FastAPI와 비동기 작업
  3. 백그라운드 작업 실행
  4. 실시간 통신을 위한 WebSockets
← FastAPI Backend Development Bootcamp(으)로 돌아가기