Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to receive data from multiple WebSockets asynchronously in Python?

I am currently trying to use the websockets library. If another library is better suited for this purpose, let me know.

Given these functions:

def handle_message(msg):
    # do something

async def consumer_handler(websocket, path):
    async for message in websocket:
        handle_message(message)

How can I (indefinitely) connect to multiple websockets? Would the below code work?

import asyncio
import websockets


connections = set()
connections.add(websockets.connect(consumer_handler, 'wss://api.foo.com', 8765))
connections.add(websockets.connect(consumer_handler, 'wss://api.bar.com', 8765))
connections.add(websockets.connect(consumer_handler, 'wss://api.foobar.com', 8765))

async def handler():
    await asyncio.wait([ws for ws in connections])

asyncio.get_event_loop().run_until_complete(handler())
like image 468
BlueOxile Avatar asked Feb 24 '26 08:02

BlueOxile


1 Answers

For anyone who finds this, I found an answer. Only works in > Python 3.6.1 I believe.

import asyncio
import websockets

connections = set()
connections.add('wss://api.foo.com:8765')
connections.add('wss://api.bar.com:8765'))
connections.add('wss://api.foobar.com:8765'))

async def handle_socket(uri, ):
    async with websockets.connect(uri) as websocket:
        async for message in websocket:
            print(message)

async def handler():
    await asyncio.wait([handle_socket(uri) for uri in connections])

asyncio.get_event_loop().run_until_complete(handler())
like image 121
BlueOxile Avatar answered Feb 25 '26 22:02

BlueOxile