How to Build a WebSocket Echo Server in Python with asyncio
Create a simple WebSocket echo server using the websockets library and asyncio to handle concurrent connections.
pip install websockets
Python code
14 linesimport asyncio
import websockets
async def echo(websocket):
async for message in websocket:
await websocket.send(f"Echo: {message}")
async def main():
async with websockets.serve(echo, "localhost", 8765):
print("WebSocket server started on ws://localhost:8765")
await asyncio.Future() # Run forever
if __name__ == "__main__":
asyncio.run(main())
Output
WebSocket server started on ws://localhost:8765
How it works
The websockets.serve coroutine starts a WebSocket server and returns an async context manager. Inside the echo handler, async for message in websocket iterates over incoming messages from the client. Each received message is sent back with an "Echo: " prefix using await websocket.send(). The main function uses asyncio.Future() to keep the server running indefinitely. The asyncio.run() ensures proper cleanup of the event loop on shutdown.
Common mistakes
- Using `asyncio.run()` with the server object directly instead of wrapping in an async main function
- Forgetting to import `websockets` even though it's a third-party package
- Not awaiting the `send` method correctly within the handler
Variations
- Use `websockets.serve` with an SSL context for wss:// support
- Implement a custom handler that logs each message before echoing
Real-world use cases
- Testing WebSocket client libraries by mocking a server locally instead of hitting a real API.
- Powering live chat features in web applications where each message is echoed for confirmation.
- Building real-time notification systems that broadcast messages to multiple connected clients.
Sponsored
More from API design & gRPC
- Build a Bulk Array POST Mock Server in Python medium
- Build a Mock REST API with PUT and GET in Python medium
- Convert Protobuf to JSON and Dict in Python easy
- Create a Data Helper in Python for gRPC-style APIs easy
- Format data in Python using dataclasses like gRPC messages easy
- Generate an OpenAPI Spec from Mock Routes in Python easy
Keep learning
Related tutorials and quizzes for this topic.