How to push notification from server (django) to client (socketio)?

1.7k Views Asked by At

I want to emit message from server to client. I have look at this but cannot use because I cannot create a namespace instance. How to emit SocketIO event on the serverside

My use case is: I have a database of price of product. A lot of users are currently surf my website. Some of them is viewing product X. On the server side, the admin can edit the price of the product. If he edit the price of X, all the client must see the notification that X price change (e.x: a simple js alert).

My client javascript now:

var socket = io.connect('/product');
#notify server that this client is viewing product X
socket.emit("join", current_product.id);

#upon receive msg from server
socket.on('notification', function (data) {
    alert("Price change"); 
}); 

My server code (socket.py):

@namespace('/products')
class ProductsNamespace(BaseNamespace, ProductSubscriberMixin):
def initialize(self, *args, **kwargs):
    _connections[id(self)] = self
    super(ProductsNamespace, self).initialize(*args, **kwargs)

def disconnect(self, *args, **kwargs):
    del _connections[id(self)]
    super(ProductsNamespace, self).disconnect(*args, **kwargs)

def on_join(self, *args):
    print "joining"

def emit_to_subscribers(self): pass

I use the runserver_socketio.py as in this link. (Thanks to Calvin Cheng for this excellent up-to-date example.)

I don't know how to call the emit_to_subscribers. Since I have no instance of namespace. As I read from this doc ,

Namespaces are created only when some packets arrive that ask for the namespace.

But how can I send the packet to that namespace from the code? IF I can only create the instance when a client emit message to server, when no one is surfing the site, right after finish editing the price, the system will fail.

I am really confused about the namespace and its instance. If you have any clearer docs, please help me.

Thanks a lot!

1

There are 1 best solutions below

0
On

This is my current state of understanding, hopefully it will be helpful to someone. Building up further from How to emit SocketIO event on the serverside, you now have a dictionary with ProductsNamespace objects as values. You can iterate through this dictionary to find the desired socket object. For example, if you set socket identifier upon connection, as described in the Django and Flask example apps by using on_nickname method, then you can retrieve the socket like so:

for key in _connections:
    socket = _connections[key]
    if 'nickname' in socket.session and socket.session['nickname'] == unicode('uniqueName'):
        socket.emit('eventTag', 'message from server')

Similarly socket.session['rooms'] can be used to emit to all members of the room, and if there are multiple SocketIO namespaces, socket.ns_name can be used.