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.

Easy Python 3.9+ Aug 9, 2026 API design & gRPC 15 views 0 copies

Requires third-party packages — install first
pip install websockets

Python code

14 lines
Python 3.9+
import 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

stdout
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

  1. Use `websockets.serve` with an SSL context for wss:// support
  2. 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

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from API design & gRPC

Related tutorials and quizzes for this topic.