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

相关内容

热门资讯

1.9分钟了解!wepoker... 自定义wepoker私人局俱乐部辅助系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专...
程序员教你!aapoker辅助... 自定义hhpoker视频巡查真的假的系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专...
盘点十款!购买wepoker模... 这是一款非常优秀的aapoker如何设置胜率 ia辅助检测软件,能够让你了解到aapoker如何设置...
实测揭晓!福建大菠萝万能辅助器... 1、实测揭晓!福建大菠萝万能辅助器,werplan怎么透视,新2025教程(有挂软件)。2、福建大菠...
最新技巧!wepoker私人局... 最新技巧!wepoker私人局俱乐部,wepoker怎么提高运气,细节揭秘(有挂方法)科技教程也叫必...
盘点一款!hhpoker有辅助... 盘点一款!hhpoker有辅助吗,德普辅助软件,辅助教程(有挂辅助)1、许多玩家不知道hhpoker...
揭秘攻略!hhpoker有辅助... 揭秘攻略!hhpoker有辅助吗,德普辅助软件,攻略教程(有挂方法);玩家必备必赢加哟《136704...
发现一款!hhpoker德州挂... 这是一款非常优秀的hhpoker德州挂真的有吗 ia辅助检测软件,能够让你了解到hhpoker德州挂...
攻略讲解!wepoker正确养... 攻略讲解!wepoker正确养号方法,黑侠破解wepoker,安装教程(有挂神器);人气非常高,ai...
最新技巧!wepoker模拟器... 最新技巧!wepoker模拟器哪个,约局吧如何查看是否有挂,透明教程(有挂攻略);科技安装教程;13...