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())
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With