Aiohttp has great websocket support:
# dictionary where the keys are user's ids, and the values are websocket connections
users_websock = {}
class WebSocket(web.View):
async def get(self):
# creating websocket instance
ws = web.WebSocketResponse()
await ws.prepare(self.request)
users_websock['some_user_id'] = ws
async for msg in ws:
# handle incoming messages
And now when I need to send a message to a special user:
# using ws.send_str() to send data via websocket connection
ws = users_websock['user_id']
ws.send_str('Some data')
That's good as long as I have only one server worker. But in production we always have multiple workers. And of course every worker has it's own different users_websock
dictionary.
So the actual problem occurs when we need send message from worker 1 to some user connected to worker 2.
And the question is how and where I should store the list of websocket connections so that each worker can get the necessary connection?
Maybe I can store in the DB some connection id or something to create websocket instance everywhere?
Or there is another way to approach this?
aiohttp doesn't provide interprocess/internode communication channels, it is another big and interesting area not related to HTTP processing itself.
You need channels between your workers. It can be Redis pubsub, RabiitMQ or even websockets -- depending on your library. Or tools like https://crossbar.io/
There is no single solution that covers all possible cases.