2

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

2 Answers 2

9

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())
Sign up to request clarification or add additional context in comments.

1 Comment

I was looking something similar with auto connect feature to ensure that the clients are always connected to the websocket Server. If the connection was closed I want the clients to re-establish the connection with the servers. For example wss://api.foobar.com:8765 websocket server was restarted. The client should reconnects automatically after few intervals. Can you help illustrate how to write such functionalities?
1

Instead of:

connections = set()

I would list it:

connections = []
connections = ["wss://api.foo.com:8765"]
connections.append ("wss://api.bar.com:8765")
connections.append ("wss://api.foobar.com:8765")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.