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客户端的消息时,它会将该消息广播

相关内容

热门资讯

玩家科普!wpk有猫腻吗,we... 玩家科普!wpk有猫腻吗,wepoke真的有挂,规律教程(总是是有挂)1.wepoke真的有挂 ai...
透视了解!wpk辅助器,微乐陕... 透视了解!wpk辅助器,微乐陕西小程序破解器,新2025教程(有挂透明)准备好在微乐陕西小程序破解器...
分享认知!wepoke app... 分享认知!wepoke app系统规律,德扑ai智能,2025教程(原本存在有挂)(1)分享认知!w...
透视透视挂!hhpoker辅助... 透视透视挂!hhpoker辅助软件下载,约战竞技场辅助软件,教你攻略(有挂方法);1分钟了解详细教程...
了解一下!wopoker透明挂... 自定义德扑之星ai代打系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅助器,不管...
透视了解!hhpoker辅助下... 透视了解!hhpoker辅助下载,广西老友玩方片破解,力荐教程(有挂软件);广西老友玩方片破解软件透...
一分钟揭秘!德扑之星系统有哪里... 一分钟揭秘!德扑之星系统有哪里规律,wepoke模拟器,透明教程(原本是有挂);人气非常高,ai更新...
透视实锤!wpk透视脚本,哥哥... 透视实锤!wpk透视脚本,哥哥打大a辅助,细节揭秘(有挂辅助);《WPK辅助透视》‌:支持手机实时对...
今日重大通报!德扑之星开房间教... 今日重大通报!德扑之星开房间教程,德州AI智能辅助机器人,攻略教程(果然真的有挂);致您一封信;亲爱...
透视苹果版!hhpoker辅助... 透视苹果版!hhpoker辅助下载,呗兔挂,AI教程(有挂透明)1、很好的工具软件,可以解锁游戏的a...