简体   繁体   English

从另一个类访问tornado websocket类方法

[英]Access tornado websocket class method from another class

I'm new to stack overflow, because I regularly found here what I've been looking for. 我是堆栈溢出的新手,因为我经常在这里找到我一直在寻找的东西。 But this time, I don't know how to handle it. 但是这次,我不知道该如何处理。 I set up a tornado websocket server and would like to access the websocket thread out of another class, but unfortunately, the websocket class requires three different arguments and isn't accessable the usual way. 我设置了一个龙卷风websocket服务器,并想从另一个类中访问websocket线程,但是不幸的是,websocket类需要三个不同的参数,并且不能以通常的方式进行访问。

class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def open(self):      
        self.loop()

    def on_message(self, message):
        #do something

    def on_close(self):
        #do something else

    def loop(self):
        pass

    def toggle(self):
        #execute

class EventHandler: 
    def __init__(self):
        self.listener()

    def listener(self):        
        def callback(channel):
            wsHandler = WebSocketHandler()
            wsHandler.toggle()

        GPIO.add_event_detect(channel, GPIO.RISING, callback = callback, bouncetime = 1000)

def main():
    EventHandler()

    application = tornado.web.Application([
        (r"/", WebSocketHandler),
    ])
    server = tornado.httpserver.HTTPServer(application)
    server.listen(8888)
    io_loop = tornado.ioloop.IOLoop.current()
    io_loop.start()

if __name__ == "__main__":
    main()

The reason why I have multiple classes is that the server should listen to input events, even if there is no client connected. 我有多个类的原因是,即使没有客户端连接,服务器也应该侦听输入事件。 But I have to transfer the input data via websocket, if there is one. 但是,如果有的话,我必须通过websocket传输输入数据。 I read about the add_callback method, but I'm not sure whether it's a useful way. 我读到有关add_callback方法的信息,但是我不确定这是否有用。

I'm glad about any solution. 我为任何解决方案感到高兴。 Thanks a lot! 非常感谢!

Alright, I used connections = [] (instead of connections = set() , because it's accessible through indexing) outside the WebsocketHandler. 好的,我在WebsocketHandler之外使用了connections = [] (而不是connections = set() ,因为它可以通过索引访问)。 To add client connections on open to the list I use connections.append(self) , to remove them on close connections.remove(self) . 为了在打开时将客户端连接添加到列表,我使用connections.append(self) ,在关闭connections.remove(self)上删除它们。

Calling the method: 调用方法:

if len(connections) > 0:
    connections[0].toggle()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM