You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多用户连接时WebSocket工作机制及Python实现相关疑问

Understanding Your Python WebSocket Server Code

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 websocket parameter passed to your handler method—each call to handler corresponds 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 handler function for that specific client.
  • The async for loop 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()—use asyncio.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:08:04