पाठ 15 / 32
WebSockets in Python with asyncio
यह पाठ अभी हिंदी में अनुवादित नहीं है, इसलिए अंग्रेज़ी में दिखाया जा रहा है।
Write an asyncio WebSocket server with the websockets library and explain how one coroutine per connection scales.
लेखक: Rahul Agarwal · 15 साल से वेब डेवलपर
One coroutine per connection
Python's popular websockets library is built on asyncio. You write a handler coroutine that receives one connection object; the library runs one handler per client. async for message in websocket waits for messages without blocking the thread, so a single process can hold thousands of idle connections, because waiting costs memory but almost no CPU. When the client disconnects, the loop ends, or a ConnectionClosed exception is raised if the close was not clean. Recent versions provide the websockets.asyncio.server.serve API used below. The catch with asyncio is that one blocking call stalls every connection: a synchronous database driver, time.sleep() or heavy CPU work inside a handler freezes all clients on that event loop. Use async drivers, await asyncio.sleep(), and asyncio.to_thread() or a process pool for CPU-bound work. Frameworks such as FastAPI and Django Channels wrap the same ideas behind their own WebSocket routes.
An echo server with websockets
Install with pip install websockets. The handler loops over incoming messages and replies to each.
import asyncio
from websockets.asyncio.server import serve
from websockets.exceptions import ConnectionClosed
async def echo(websocket):
try:
async for message in websocket:
await websocket.send(f"echo: {message}")
except ConnectionClosed:
pass # client went away without a clean close
async def main():
async with serve(echo, "localhost", 8765) as server:
await server.serve_forever()
if __name__ == "__main__":
asyncio.run(main())Find blocking calls early
Run the event loop in debug mode with PYTHONASYNCIODEBUG=1 (or asyncio.run(main(), debug=True)). asyncio then logs callbacks that take longer than 100 ms, which points straight at the blocking call.
One waiter, many tables
An asyncio server is a single efficient waiter serving many tables: while one table reads the menu, the waiter takes another order. If the waiter stops to cook a dish personally, every table waits. CPU-heavy work belongs in the kitchen, meaning a thread or process pool.
त्वरित जाँच: Inside an asyncio WebSocket handler, a developer calls `time.sleep(2)`. What happens?
- Only that client waits 2 seconds
- The library automatically moves it to a thread
- Every connection served by that event loop is frozen for 2 seconds
- The connection is closed with code 1011
Answer
Every connection served by that event loop is frozen for 2 seconds — `time.sleep` blocks the single event loop thread, so no other coroutine can run. Use `await asyncio.sleep(2)` instead.