簡體   English   中英

同時處理 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())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM