You need to enable JavaScript to run this app. Python websockets库扩展最大连接数至3000+ 解决高并发崩溃问题
优惠活动
大模型
产品
解决方案
定价
更多

Python websockets库扩展最大连接数至3000+ 解决高并发崩溃问题

问题根因

你遇到的崩溃核心是两层限制:

  • Windows系统下select()系统调用默认最大仅支持512个文件描述符,超过就会抛出too many file descriptors in select()报错
  • Linux系统下默认select()调用上限为1024,同时系统默认单进程打开文件描述符上限也为1024,双重限制导致连接到1019左右崩溃
修复方案(Linux环境优先,可稳定支持3000-4000并发)

1. 调整系统文件描述符上限

临时生效(重启后恢复):

ulimit -n 65535

永久生效:
编辑/etc/security/limits.conf,在末尾添加两行:

* soft nofile 65535
* hard nofile 65535

保存后重启服务器生效,如果服务是systemd管理,还要在service配置的[Service]段添加LimitNOFILE=65535,重载systemd配置后重启服务。

2. 替换默认asyncio事件循环为更高性能的uvloop

uvloop是C实现的asyncio事件循环,性能比默认loop高2-4倍,原生支持高并发连接,无需依赖select调用的1024限制:

  • 先安装uvloop:
pip install uvloop
  • 修改server.py代码,在导入模块后添加loop替换逻辑,同时优化原有通知逻辑的性能:
#!/usr/bin/env python
# WS server example that synchronizes state across clients
import asyncio
import json
import logging
import websockets
import uvloop

# 替换默认事件循环
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

logging.basicConfig()

STATE = {"value": 0}
USERS = set()

def state_event():
    return json.dumps({"type": "state", **STATE})

def users_event():
    return json.dumps({"type": "users", "count": len(USERS)})

async def notify_state():
    if USERS:
        message = state_event()
        # 用gather替代wait,高并发下性能更优,忽略断开连接的异常
        await asyncio.gather(*[user.send(message) for user in USERS], return_exceptions=True)

async def notify_users():
    if USERS:
        message = users_event()
        await asyncio.gather(*[user.send(message) for user in USERS], return_exceptions=True)

async def register(websocket):
    USERS.add(websocket)
    print("add")
    await notify_users()

async def unregister(websocket):
    USERS.remove(websocket)
    await notify_users()

async def counter(websocket, path):
    await register(websocket)
    try:
        await websocket.send(state_event())
        async for message in websocket:
            data = json.loads(message)
            if data["action"] == "minus":
                STATE["value"] -= 1
                await notify_state()
            elif data["action"] == "plus":
                STATE["value"] += 1
                await notify_state()
            else:
                logging.error("unsupported event: %s", data)
    finally:
        await unregister(websocket)

start_server = websockets.serve(counter, "0.0.0.0", 12345)
loop = asyncio.get_event_loop()
loop.run_until_complete(start_server)
loop.run_forever()

3. 压测端同步调整

你使用的压测脚本本身也会占用大量文件描述符,压测前也需要调整压测机器的文件描述符上限,避免压测端先崩溃。同时建议不要用list作为变量名,这是Python内置关键字,容易引发未知问题。

Windows环境临时解决方案

如果需要在Windows下做测试,可手动将事件循环替换为ProactorEventLoop,突破512连接限制:

import asyncio
asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())

但Windows系统本身的网络模型性能远低于Linux,不建议用于生产环境高并发场景。


内容的提问来源于stack exchange,提问作者Damirnar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 11:24:10