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

相关内容

热门资讯

透视模拟器"poke... 透视模拟器"pokemmo手机辅助软件"详细辅助2025教程(破解器有用方法)是一款可以让一直输的玩...
透视好友"aa po... 透视好友"aa poker辅助包"详细辅助透明挂教程(智能辅助插件技巧)准备好在aa poker辅助...
透视最新"哈糖大菠萝... 透视最新"哈糖大菠萝怎么开挂"详细辅助透明教程(免费透视脚本软件)1、点击下载安装,微扑克wpk插件...
透视讲解"wepok... 1、透视讲解"wepokerplus透视脚本免费"详细辅助安装教程(透视方法辅助)。2、wepoke...
透视工具"德州私人局... 透视工具"德州私人局脚本"详细辅助靠谱教程(插件功能辅助器方法);原来确实真的有挂(需添加指定薇13...
透视软件"德州机器人... 透视软件"德州机器人代打脚本"详细辅助AI教程(辅助器安装包定制技巧)准备好在德州机器人代打脚本 i...
透视新版"wepok... 透视新版"wepoker免费透视脚本"详细辅助大神讲解(游戏下载透视),支持语音通讯、好友开房及战队...
透视肯定"hhpok... 透视肯定"hhpoker免费透视脚本"详细辅助力荐教程(私人局俱乐部辅助技巧);科技安装教程;136...
透视私人局"wepo... 透视私人局"wepoker私人局俱乐部辅助"详细辅助教你攻略(透视脚本免费软件);小薇(透视辅助)致...
透视讲解"hhpok... 透视讲解"hhpoker软件靠谱吗"详细辅助大神讲解(淘宝买透视有用技巧)准备好在hhpoker软件...