WebSockets เพื่อการสื่อสารแบบเรียลไทม์
สร้างฟีเจอร์แบบเรียลไทม์ใน FastAPI ด้วย WebSockets รับการเชื่อมต่อ แลกเปลี่ยนข้อความ กระจายข้อความไปยังไคลเอนต์จำนวนมาก และจัดการการตัดการเชื่อมต่ออย่างเรียบร้อยด้วยรูปแบบอะซิงโครนัส
WebSockets เพื่อการสื่อสารแบบเรียลไทม์ เป็นบทเรียน FastAPI Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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
WebSocketDisconnectcleanly. - Built a connection manager to broadcast to many clients.
- Learned to scale with Redis pub/sub and to secure connections.
คำถามที่พบบ่อย
บทเรียน “WebSockets เพื่อการสื่อสารแบบเรียลไทม์” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “WebSockets เพื่อการสื่อสารแบบเรียลไทม์” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส FastAPI Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “WebSockets เพื่อการสื่อสารแบบเรียลไทม์”
สร้างฟีเจอร์แบบเรียลไทม์ใน FastAPI ด้วย WebSockets รับการเชื่อมต่อ แลกเปลี่ยนข้อความ กระจายข้อความไปยังไคลเอนต์จำนวนมาก และจัดการการตัดการเชื่อมต่ออย่างเรียบร้อยด้วยรูปแบบอะซิงโครนัส คุณปฏิบัติ FastAPI Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน FastAPI Backend Development Bootcamp หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน FastAPI Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน
บทเรียน “WebSockets เพื่อการสื่อสารแบบเรียลไทม์” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน FastAPI Backend Development Bootcamp นี้ได้ไหม
ได้ บทเรียน FastAPI Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- ทบทวน Async/Await ใน Python
- FastAPI และการทำงานแบบอะซิงโครนัส
- การทำงานเบื้องหลัง
- WebSockets เพื่อการสื่อสารแบบเรียลไทม์