Home > front end >  Best way to handle 2 websocket connections in the same time
Best way to handle 2 websocket connections in the same time

Time:05-15

i am handling data from 2 websocket servers and i would like to know whats the fastest way to handle both connections in the same time given that the 1st connection would send data every 0.1-10ms.

what i am doing so far is:

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())

CodePudding user response:

As stated in the comments, try to handle each connection in its own coroutine. Here is small example:

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())
  • Related