简体   繁体   English

在Tornado Websockets服务器上共享价值

[英]Share a value across Tornado Websockets server

I have a basic websocket server using Tornado framework in python. 我有一个在Python中使用Tornado框架的基本websocket服务器。 I want to share a value between the server functions: 我想在服务器功能之间共享一个值:

class EchoWebSocket(websocket.WebSocketHandler):

    def check_origin(self, origin):
        return True
    def open(self):
        print ("connection opened")
    def on_close(self):
        tornado.ioloop.IOLoop.instance().stop()
        print ("connection closed")
    def on_message(self,message):
        print (message)

def Main():
    application = tornado.web.Application([(r"/", EchoWebSocket),])
    application.listen(9000)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    Main() 

I tried to create a global object from a class like this: 我试图从这样的类创建一个全局对象:

class operate:
    state = "mutual"

    def __init__(self):
        self.state = 'mutual'

    def play(self):
        self.state = 'play'

    def pause(self):
        self.state = 'pause'

    def getStatus(self):
        return self.state 

and call a global object, guessing that since the object is global it will be the same not creating a new one every message: 并调用一个全局对象,猜测由于该对象是全局对象,因此不会在每条消息中都创建一个新对象是相同的:

def open(self):
    global objectTV
    objectTV = operate()
    objectTV.play()
.
.
.
.
 def on_message(self,message):
        global objectTV
        objectTV = operate()
        print(objectTV.getStatus())

But it always print 'mutual'? 但是它总是打印“相互”吗?

In the method on_message() , every time a new message arrives, you're instantiating objectTV again and again at objectTv = operate() . on_message()方法中,每次on_message()新消息时,您都会在objectTv = operate()处一次又一次地实例化objectTV The new instance of operate class has the initial state set to 'mutual' , that is why it's printing 'mutual' . 新的operate类实例的初始状态设置为'mutual' ,这就是为什么它打印'mutual'

A simple fix would be to remove objectTV = operate() line from on_message() and it should work like you want it to. 一个简单的修复方法是从on_message()删除objectTV = operate()行,并且它应该可以像您希望的那样工作。

But read some answers on this question: Why are global variables evil? 但是请阅读有关此问题的一些答案: 为什么全局变量有害? .

So, the better approach to solve your problem would be to set a local attribute on the handler instance instead: 因此,解决问题的更好方法是在处理程序实例上设置本地属性:

class EchoWebSocket(websocket.WebSocketHandler):
    ...
    def open(self):
        self.objectTV = operate()
        self.objectTV.play()

    def on_message(self, message):
        print(self.objectTV.getStatus()) # -> 'play'

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

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