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