AsyncioPythonWebSocket服务器有两个WebSocket(其中一个总是关闭连接)
创始人
2024-09-21 07:00:28
0

以下是一个示例代码,可用于创建一个包含两个WebSocket的Asyncio Python WebSocket服务器,并模拟其中一个WebSocket始终关闭连接的情况。

import asyncio
import websockets

# 客户端id列表
client_list = []

async def handle_websocket(websocket, path):
    # 将新连接的客户端id添加到client_list中
    client_id = id(websocket)
    client_list.append(client_id)
    print(f'New connection from client {client_id}')

    try:
        while True:
            # 接收客户端发送的消息
            message = await websocket.recv()
            print(f'Received message from {client_id}: {message}')

            # 广播消息给所有客户端
            for cid in client_list:
                if cid == client_id:
                    continue
                try:
                    # 发送消息给其他客户端
                    await asyncio.wait_for(websockets.connect(f'http://localhost:8000/{cid}'), timeout=5)
                    await websocket.send(f'From {client_id}: {message}')
                except websockets.exceptions.ConnectionClosedError:
                    # 如果连接已关闭,则将其从client_list中删除
                    client_list.remove(cid)

    finally:
        # 如果websocket连接已关闭,则将其从client_list中删除
        client_list.remove(client_id)
        print(f'Connection closed from client {client_id}')

async def main():
    # 创建两个WebSocket
    ws_server = websockets.serve(handle_websocket, 'localhost', 8000)
    ws_client = websockets.connect('ws://localhost:8000/')

    # 在后台启动WebSocket服务器
    async with ws_server:
        await ws_server.start_serving()
    
    # 在后台启动WebSocket客户端
    async with ws_client:
      while True:
          # 持续发送消息到服务器
          await ws_client.send('Hello, world!')

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

由于WebSocket客户端始终保持连接,因此当WebSocket服务器收到来自WebSocket客户端的消息时,它会将该消息广播

相关内容

热门资讯

重大科普!wepoker透视底... 重大科普!wepoker透视底牌脚本(辅助挂)确实是真的有挂(有挂方针)1、完成wepoker透视底...
重大消息!悦扑克脚本(辅助挂)... 重大消息!悦扑克脚本(辅助挂)真是是有挂(存在有挂)1、悦扑克脚本免费辅助多个强度级别选择2、悦扑克...
一分钟了解!wepoker智能... 您好,wepoker智能辅助插件这款游戏可以开挂的,确实是有挂的,需要了解加去威信【13670430...
重大通报!wepoker轻量版... 重大通报!wepoker轻量版辅助(辅助挂)本来存在有挂(发现有挂)wepoker轻量版辅助辅助器是...
交流学习经验!hhpkoer辅... 交流学习经验!hhpkoer辅助挂是真的吗(辅助挂)都是有挂(有挂方法)hhpkoer辅助挂是真的吗...
推荐一款!aapoker透视脚... 推荐一款!aapoker透视脚本下载(辅助挂)本来有挂(有挂辅助)运aapoker透视脚本下载辅助工...
记者发布!aapoker透视脚... 记者发布!aapoker透视脚本下载(辅助挂)好像真的是有挂(有挂规律)1、玩家可以在aapoker...
实测揭晓!wepoker辅助器... 实测揭晓!wepoker辅助器激活码(辅助挂)总是有挂(有挂实锤)1、进入到wepoker辅助器激活...
一分钟揭秘!hhpoker透视... 一分钟揭秘!hhpoker透视工具(辅助挂)本来真的是有挂(有挂详情)1、hhpoker透视工具模拟...
今日百科!wejoker黑侠辅... 今日百科!wejoker黑侠辅助器(辅助挂)总是是真的有挂(有挂讲解)1、游戏颠覆性的策略玩法,独创...