10.4 WebSocket 连接管理
FastAPI WebSocket Connection Management for Beginners: Step-by-Step Tutorial
A beginner-friendly guide to managing WebSocket connections in FastAPI. Learn with simple examples, life analogies, and hands-on practice to build confidence in creating real-time applications.
FastAPI WebSocket Connection Management for Beginners
Introduction: What Are WebSockets?
Imagine you're having a phone call with a friend. You can talk back and forth instantly without hanging up. That's what WebSockets are like in web development! Unlike traditional HTTP, which is like sending letters back and forth (request and response), WebSockets keep a persistent connection open for real-time two-way communication. This is perfect for chat apps, live notifications, or games.
Why This Tutorial? You know basic Python, and we'll jump straight into building things—no boring theory! By the end, you'll have working WebSocket code you can play with.
Getting Started: Setup Your Environment
First, make sure Python is installed (version 3.7 or higher is recommended). Then, open your terminal and install FastAPI and a server called Uvicorn.
pip install fastapi uvicorn
Success Moment: You've just installed the tools! This is like getting your kitchen ready before cooking—simple but essential.
Creating Your First WebSocket Endpoint
Let's write a simple FastAPI app that uses WebSockets. Create a new file named main.py and add this code:
from fastapi import FastAPI, WebSocket
app = FastAPI() # This creates your web app
@app.websocket("/ws") # This sets up a WebSocket endpoint at /ws
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept() # Step 1: Accept the incoming connection
while True:
data = await websocket.receive_text() # Step 2: Wait for a message
await websocket.send_text(f"Echo: {data}") # Step 3: Send it back
Run the server: In your terminal, navigate to the folder with main.py and run:
uvicorn main:app --reload
Test It: You can use an online WebSocket tester or write a small Python script. For now, just trust that it works! This echoes any message you send.
Success Moment: You've built a WebSocket server! It's like making a simple walkie-talkie—send a message, hear it back instantly.
Understanding Connection Lifecycles with an Analogy
Think of WebSocket connections as guests at a party:
- Connect: A guest arrives (connection is accepted with
websocket.accept()). - Message: They chat with you (send/receive data in a loop).
- Disconnect: They leave (connection closes).
In our code, the while True loop keeps the conversation going until something breaks.
Managing Multiple Connections: Build a Simple Chat Room
Now, let's handle multiple guests. We'll store active connections in a list and broadcast messages to everyone.
Update main.py:
from fastapi import FastAPI, WebSocket
from typing import List # Import List to manage connections
app = FastAPI()
# A list to keep track of all connected clients, like a guest list
connections: List[WebSocket] = []
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
connections.append(websocket) # Add new connection to the list
try:
while True:
data = await websocket.receive_text()
# Broadcast to all connected clients
for connection in connections:
await connection.send_text(f"Someone said: {data}")
except:
connections.remove(websocket) # Remove if disconnected
Success Moment: You've created a mini chat room! Every message is sent to all users. Run the server and test with multiple browser tabs or tools—it's fun to see real-time updates.
Practical Example: Adding User Names and Better Disconnection Handling
Let's make it more realistic. We'll add a simple way to handle users leaving properly.
Modify the code slightly:
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
connections.append(websocket)
try:
while True:
data = await websocket.receive_text()
# Send to others only, so you don't see your own message echoed
for connection in connections:
if connection != websocket:
await connection.send_text(f"New message: {data}")
except Exception as e:
print(f"Error: {e}") # Log errors
finally:
connections.remove(websocket)
await websocket.close() # Close connection gracefully
Success Moment: Now your chat room is more polished! Errors are handled, and connections close cleanly—like saying goodbye properly at the party.
Best Practices and Tips
- Always Close Connections: Use
finallyto ensure connections are removed and closed, even if errors occur. - Keep It Simple: Start with basic examples; you can add features like authentication or private rooms later.
- Test Often: Use WebSocket client tools to see things in action—it boosts confidence!
Conclusion and Next Steps
You've learned how to set up WebSockets in FastAPI, manage connections, and build a simple real-time app. This is a solid foundation!
What to Do Next:
- Experiment by adding user names or message history.
- Check the FastAPI documentation for more advanced WebSocket features.
- Try integrating with a frontend like JavaScript to make a full chat app.
Remember, every line of code you write is a step towards becoming a web developer. Keep building and having fun!
Happy coding! 🚀