Closed wiesson closed 8 years ago
Because flask-sockets relies on gunicorn, you will need to use some additional piece of infrastructure outside of your flask app to be able to access that kind of information from a websocket endpoint. Gunicorn uses the "prefork worker model", which means one master process handles a set of worker processes to respond to requests. This means that objects in memory in one request will not be accessible from another. So if you wanted one websocket to send a message when another one connects to the server, you would need some thing that can save changes from one process and share them with another process. (A lot of websites use memcache for this purpose.) One good option for doing this with flask-sockets is redis, which comes with support for a publish-subscribe system. Using redis with pubsub would involve subscribing a new websocket to a redis publishing feed, and publishing to that feed whenever you want the user's socket to send a message to their browser. Hope that helps!
Thank you for your answer! So, I'm basically looking for an option to send e.g. notifications that something has happened or is ready (from a long pulling thread or so) to a logged in user (specific one) or also to users that are currently viewing a specific page. Currently I'm just pushing lots of information to a websocket and all users are getting those information. Not that efficient ;) I will take a look at redis. Thanks!
Here's an example backend you can get started with: https://github.com/heroku-examples/python-websockets-chat/blob/master/chat.py#L28
I am following the above example and a little help would be appreciated. I want to send messages to a single client only. How do I distinguish between clients? Can I assign identifiers to clients and select a client based on an id? For example when in the run
function instead of for client in self.clients:
I would want something like client=self.client_by_id(id)
. Or should I just make a new channel for every socket?
How could I send a message to a single client that is connected? I'm looking for something to send a notification to a logged in user that something is ready or so. Ideas?