如何在服务器端发出SocketIO事件 [英] How to emit SocketIO event on the serverside

查看:407
本文介绍了如何在服务器端发出SocketIO事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个gevent-socketio Django应用程序。



我有类似于这个类的东西

  @namespace('/ connect')
class ConnectNamespace(BaseNamespace):

def on_send(self,data):
#。 ..

但是,如果我收到来自JavaScript客户端的事件,一切正常,例如 send 事件处理正确



如果我想要 emit 服务器端的某些事件。我可以在课程中使用 socket.send_packet



,但现在我想将一些事件链接到code> post_save signal,所以我想从这个命名空间类之外的 send_packet ,这样做的一种方式是

  ConnectNamespaceInstance.on_third_event('someeventname')

我不知道如何获取ConnectNamespaceInstance的实例



总而言之,我只想发送一个事件到javascript客户端收到 post_save 信号

解决方案

你可能想要什么要做的是添加一个模块变量来跟踪连接,例如 _connections ,像这样:

  _connections = {} 

@namespace('/ connect')
class ConnectNamespace(BaseNamespace):

,然后添加 initialize disconnect 你可以稍后参考一些快乐标识符:

  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)

当您需要生成事件时,您可以在 _connections 变量中查找正确的连接,然后将其关闭事件与 emit



(没有测试任何这个,但我使用了类似的模式许多其他语言:没有看到任何原因为什么这不会在Python中工作)。


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

解决方案

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

这篇关于如何在服务器端发出SocketIO事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆