WebSocket Server sending messages periodically in python

后端 未结 3 1400
刺人心
刺人心 2021-01-14 05:53

I have a tornado web server in python:

import tornado.httpserver
import tornado.websocket
import tornado.ioloop
from tornado.ioloop import IOLoop
import tor         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-14 06:08

    Here's a minimal example using the PeriodicCallback.

    import tornado.httpserver
    import tornado.websocket
    import tornado.ioloop
    from tornado.ioloop import PeriodicCallback
    import tornado.web
    
    class WSHandler(tornado.websocket.WebSocketHandler):
        def open(self):
            self.callback = PeriodicCallback(self.send_hello, 120)
            self.callback.start()
    
        def send_hello(self):
            self.write_message('hello')
    
        def on_message(self, message):
            pass
    
        def on_close(self):
            self.callback.stop()
    
    application = tornado.web.Application([
        (r'/', WSHandler),
    ])
    
    if __name__ == "__main__":
        http_server = tornado.httpserver.HTTPServer(application)
        http_server.listen(8888)
        tornado.ioloop.IOLoop.instance().start()
    

提交回复
热议问题