python - Tornado - Send message to client on demand -
i'm using tornado serve html file and, @ same time, want python program dynamically change value in same page through websockets. purpose value can seen changing, without need refresh on client side.
in case, want send message variable changes "1234" "4321" every 4 seconds. have thread doing value toggling , want same thread send value websocket, can handle script using onmessage function in client side.
the following code give me following error: 'application' object has no attribute 'write_message'
import tornado.ioloop import tornado.web import tornado.websocket import threading import time flag = true class mainhandler(tornado.web.requesthandler): def get(self): self.render("mypage.html") class wshandler(tornado.websocket.websockethandler): def open(self): self.write_message('connected') print "websocket opened" def on_message(self, message): self.write_message("you have sent: " + message) def on_close(self): print "websocket closed" def write_message(self, message): print ("writing message", message) self.write_message(message) application = tornado.web.application( handlers=[ (r"/", mainhandler), (r"/ws", wshandler), ]) def toggle(): global flag while true: if flag==true: print 'now on 1234' flag = false application.write_message('1234') time.sleep(4) elif flag==false: flag = true application.write_message('4321') print 'now on 4321' time.sleep(4) def main(): global response valuethread=threading.thread(target=toggle, name="toggle value thread") valuethread.setdaemon(true) valuethread.start() application.listen(8888) tornado.ioloop.ioloop.instance().start() if __name__ == "__main__": main()
my problem every single tutorial/guide i've seen tornado uses function write_message within open , onmessage function within websocket class.. don't why won't work.
you should only use function write_message within open , onmessage function within websocket class. using application
, tornado.web.application
. won't have method of tornado.websocket.websockethandler
. not same class. hence error.
i like:
class wshandler(tornado.websocket.websockethandler): def toggle(self): flag = true while true: if flag==true: print 'now on 1234' flag = false self.write_message('1234') time.sleep(4) elif flag==false: flag = true self.write_message('4321') print 'now on 4321' time.sleep(4) def on_message(self, message): if message == 'toggle': self.toggle()
Comments
Post a Comment