多用户连接时WebSocket工作机制及Python实现相关疑问
First, let's clean up your example code to make it complete (since it was cut off):
import os import asyncio import websockets class Server: def get_port(self): return os.getenv('WS_PORT', '8765') def get_host(self): return os.getenv('WS_HOST', 'localhost') def start(self): return websockets.serve(self.handler, self.get_host(), self.get_port()) async def handler(self, websocket, path): async for message in websocket: print('server received :', message) await websocket.send(message) if __name__ == '__main__': ws = Server() asyncio.get_event_loop().run_until_complete(ws.start()) asyncio.get_event_loop().run_forever()
Does This Follow the TCP Socket Passive/Active Model?
Absolutely—this aligns perfectly with the TCP socket model you’re familiar with:
- Passive Socket: The
websockets.serve()function creates a listening TCP socket (your passive socket) bound to the host and port you specify. This socket sits idle until a client sends a connection request. - Active Sockets per Client: Every time a client successfully connects, the library spins up a new TCP connection (active socket) for that client. This connection is wrapped in the
websocketparameter passed to yourhandlermethod—each call tohandlercorresponds to a unique client, with its own dedicated WebSocket (built on top of TCP) instance.
The websockets library just handles the low-level handshake and framing for you, but the underlying TCP socket behavior is exactly what you’d expect.
How Does the Server Handle Multiple Concurrent Users?
This asyncio-based server handles multiple connections efficiently using concurrent tasks, no separate threads required (though it can integrate with threads if needed):
- When a new client connects, the server spawns an async task that runs your
handlerfunction for that specific client. - The
async forloop in the handler lets the event loop pause processing for one client when it’s waiting for a message (or sending one), and switch to handling tasks for other clients in the meantime. - This non-blocking approach means your server can support hundreds or thousands of concurrent connections, as long as your handler code avoids blocking calls (like
time.sleep()—useasyncio.sleep()instead if you need delays).
For example: While waiting for Client A to send its next message, the event loop can process incoming messages from Client B, send responses to Client C, and accept a new connection from Client D—all without any of these operations blocking each other.
内容的提问来源于stack exchange,提问作者Kev1n91

