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

相关内容

热门资讯

线上(wepoke真的)原来是... 线上(wepoke真的)原来是真的有挂!其实真的有挂(2022已更新)(哔哩哔哩);亲,其实确实真的...
两教程(Wepoke程序)软件... 两教程(Wepoke程序)软件透明挂辅助工具(软件透明挂)透视辅助(2024已更新)(哔哩哔哩);致...
软件(wepoke透明)原来是... 软件(wepoke透明)原来是真的有挂!其实真的有挂(2020已更新)(哔哩哔哩)是一款可以让一直输...
一模拟器(德扑工具)外挂辅助工... 一模拟器(德扑工具)外挂辅助工具(透视)透视辅助(2025已更新)(哔哩哔哩);亲真的是有正版授权,...
系统(aapoker讲解)竟然... 系统(aapoker讲解)竟然真的有挂!其实真的有挂(2021已更新)(哔哩哔哩);aapoker讲...
6系统(aapoker下载)外... 6系统(aapoker下载)外挂辅助工具(辅助挂)透视辅助(2023已更新)(哔哩哔哩)aapoke...
智能(德扑之星刷数据)果真真的... 智能(德扑之星刷数据)果真真的有挂!原来真的有挂(2025已更新)(哔哩哔哩);《WPK辅助透视》‌...
1机器人(德州nzt软件)软件... 1机器人(德州nzt软件)软件透明挂辅助软件(透视)透视辅助(2022已更新)(哔哩哔哩);人气非常...
ai代打(德扑之星决策)确实是... ai代打(德扑之星决策)确实是真的有挂!原来真的有挂(2020已更新)(哔哩哔哩);科技详细教程小薇...
第8透明(wepoke数据)外... 第8透明(wepoke数据)外挂透明挂辅助神器(辅助挂)透视辅助(2023已更新)(哔哩哔哩);原来...