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私局代打,wepoker怎么买辅助,靠谱教程(有挂软件)准备好在wepoke...
总算了解!we poker游戏... 总算了解!we poker游戏下,hhpoker透视脚本下载,2025版教程(有挂技巧);人气非常高...
总算了解!wepoker破解器... 总算了解!wepoker破解器激活码,aapoker免费透视脚本,揭秘教程(有挂攻略);支持多人共享...
推荐一款!德州透视插件,wej... 推荐一款!德州透视插件,wejoker黑侠辅助器,透视教程(有挂技巧);人气非常高,ai更新快且高清...
实测教程!hhpoker辅助器... 1、实测教程!hhpoker辅助器,hh poker插件下载,必备教程(有挂辅助)2、进入游戏-大厅...
一分钟揭秘!拱趴大菠萝挂,xp... 一分钟揭秘!拱趴大菠萝挂,xpoker辅助助手,安装教程(有挂技巧),支持语音通讯、好友开房及战队组...
玩家攻略!wepokerplu... 玩家攻略!wepokerplus开挂,wpk透视辅助下载,揭秘教程(有挂透视)关于wpk透视辅助下载...
记者发布!pokemmo脚本辅... 记者发布!pokemmo脚本辅助器下载,aapoker脚本怎么用,普及教程(有挂软件);实战中需综合...
分享开挂内幕!拱趴游戏破解器,... 1、分享开挂内幕!拱趴游戏破解器,pokemmo脚本辅助下载,线上教程(有挂辅助)。2、pokemm...
推荐十款!wepoker私人局... 您好,wepoker私人局辅助挂这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】...