同时处理 2 个 websocket 连接的最佳方法

Best way to handle 2 websocket connections in the same time

我正在处理来自 2 个 websocket 服务器的数据,我想知道同时处理两个连接的最快方法是什么,因为第一个连接每 0.1-10 毫秒发送一次数据。

目前我正在做的是:

import json
import websockets

async def run():
    async with websockets.connect("ws://localhost:8546/") as ws1:
        async with websockets.connect(uri="wss://api.blxrbdn.com/ws", extra_headers = {"Authorization": "apikey") as ws2:

            sub1 = await ws1.send("subscription 1")
            sub2 = await ws2.send("subscription 2")

            while True:
                try:
                    msg1 = await ws1.recv()
                    msg1 = json.loads(msg1)

                    msg2 = await ws2.recv()
                    msg2 = json.loads(msg2)

                    # process msg1 & msg2
                except Exception as e:
                    print(e, flush=True)

asyncio.run(run())

如评论中所述,尝试在其自己的协程中处理每个连接。这是一个小例子:

import asyncio
import websockets


async def worker(ws, msg, t):
    while True:
        sub = await ws.send(msg)
        print("Received from the server:", await ws.recv())
        await asyncio.sleep(t)


async def run():
    url1 = "ws://localhost:8765/"
    url2 = "ws://something_different:8765/"

    async with websockets.connect(url1) as ws1, websockets.connect(url2) as ws2:
        await asyncio.gather(worker(ws1, "sub1", 1), worker(ws2, "sub2", 2))


asyncio.run(run())