I'm running a gevent-socketio Django application.
I have something similar to this class
@namespace('/connect')
class ConnectNamespace(BaseNamespace):
def on_send(self, data):
# ...
However, if I receive the events from the javascript client, everything works and for instance send
event is processed correctly
I'm a little bit lost if I want to emit
some event on the server side. I can do it inside the class with socket.send_packet
But now I want to link some event to post_save
signal, so I'd like to send_packet
from outside this namespace class, one way of doing this would be
ConnectNamespaceInstance.on_third_event('someeventname')
I just can't figure out how can I get the instance of ConnectNamespaceInstance
To sum it up, I just want to send an event to javascript client after I receive post_save
signal
To emit an event from your client, use the emit function on the socket object. To handle these events, use the on function on the socket object on your server. Sent an event from the client!
var socket = require('socket. io-client')('ws://ws.website.com/socket.io/?EIO=3&transport=websocket'); socket. on('connect', function() { console. log("Successfully connected!"); });
JS, Socket.IO enables asynchronous, two-way communication between the server and the client. This means that the server can send messages to the client without the client having to ask first, as is the case with AJAX.
Socket.io, and WebSockets in general, require an http server for the initial upgrade handshake. So even if you don't supply Socket.io with an http server it will create one for you.
What you probably want to do is add a module variable to track connections, say _connections
, like so:
_connections = {}
@namespace('/connect')
class ConnectNamespace(BaseNamespace):
and then add initialize
and disconnect
methods that use some happy identifier you can reference later:
def initialize(self, *args, **kwargs):
_connections[id(self)] = self
super(ConnectNamespace, self).initialize(*args, **kwargs)
def disconnect(self, *args, **kwargs):
del _connections[id(self)]
super(ConnectNamespace, self).disconnect(*args, **kwargs)
When you need to generate an event, you can then just look up the right connection in the _connections
variable, and fire off the event with emit
.
(Didn't test any of this, but I've used a similar pattern in many other languages: don't see any reason why this wouldn't work in Python as well).
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