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

如何在单个Python脚本中同时运行多个WebSocket服务?

如何在单个Python脚本中同时运行多个WebSocket服务?

嗨,我懂你的困扰——现在你的代码启动第一个WebSocket服务后就卡着不动,根本没机会启动后面的服务,对吧?这是因为你在第一个async with serve(...)块里await了一个永远不会完成的create_future(),程序直接被卡在这儿,没机会执行后续代码。

其实用asyncio和websockets完全能在单个脚本里同时跑多个WebSocket服务,我给你分享两种实用的方法:

方法一:收集服务任务,用asyncio.gather统一等待

这种方法兼容性强,不管你用哪个版本的Python都能跑。核心思路是:每个WebSocket服务启动后会返回一个Server对象,调用它的wait_closed()方法能得到一个等待服务关闭的异步任务,把所有服务的这类任务收集起来,最后一起等待,就能让所有服务同时运行了。

示例代码(先写两个服务,剩下4个照着抄就行):

import asyncio
import json
from websockets.server import serve

# 第一个端口的专属处理逻辑
async def handle_socket_20781(websocket, path):
    print(f"A client just connected to 20781 {path}")
    welcome_msg = {"socket_port": 20781, "msg": "Welcome to port 20781!"}
    await websocket.send(json.dumps(welcome_msg))
    # 可以添加消息交互逻辑,比如接收客户端消息并回复
    async for message in websocket:
        await websocket.send(f"[20781] Received your message: {message}")

# 第二个端口的专属处理逻辑
async def handle_socket_20782(websocket, path):
    print(f"A client just connected to 20782 {path}")
    welcome_msg = {"socket_port": 20782, "msg": "Welcome to port 20782!"}
    await websocket.send(json.dumps(welcome_msg))
    async for message in websocket:
        await websocket.send(f"[20782] Received your message: {message}")

# 剩下4个端口的处理函数照着上面的格式定义即可...

async def main():
    running_tasks = []
    
    # 启动第一个服务,把等待关闭的任务加入列表
    server_20781 = await serve(handle_socket_20781, "localhost", 20781)
    print("WebSocket server started on port 20781")
    running_tasks.append(server_20781.wait_closed())
    
    # 启动第二个服务,同样添加任务
    server_20782 = await serve(handle_socket_20782, "localhost", 20782)
    print("WebSocket server started on port 20782")
    running_tasks.append(server_20782.wait_closed())
    
    # 继续添加剩下4个服务的启动代码...
    
    # 等待所有服务保持运行,直到手动终止程序
    await asyncio.gather(*running_tasks)

if __name__ == "__main__":
    asyncio.run(main())

方法二:用异步上下文管理器同时启动多服务(Python 3.10+支持)

如果你用的是Python 3.10或更高版本,可以用更简洁的写法:把多个serve调用放在同一个async with块里,用逗号分隔,所有服务会同时启动,再用一个永不完成的future让程序保持运行。

示例代码:

import asyncio
import json
from websockets.server import serve

# 处理函数定义和方法一一致,这里省略...

async def main():
    # 同时启动多个WebSocket服务
    async with (
        serve(handle_socket_20781, "localhost", 20781),
        serve(handle_socket_20782, "localhost", 20782),
        # 把剩下4个服务的serve调用也加在这里...
    ):
        print("All WebSocket servers are running!")
        # 保持程序运行,直到手动停止
        await asyncio.get_running_loop().create_future()

if __name__ == "__main__":
    asyncio.run(main())

这两种方法都能让你在单个脚本里同时运行多个独立的WebSocket服务,不用开6个单独的脚本。每个服务的处理逻辑可以根据需求单独定制,完全互不影响。

备注:内容来源于stack exchange,提问作者Jonathan Gilpin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 16:03:04