python - Sending messages actively from Tornado WebSocket server -
i have python websocket server. can return response when receives message.
import tornado.web import tornado.websocket import tornado.ioloop class websockethandler(tornado.websocket.websockethandler): def open(self): print("new client connected") self.write_message("you connected") def on_message(self, message): self.write_message(u"you said: " + message) def on_close(self): print("client disconnected") def check_origin(self, origin): return true application = tornado.web.application([ (r"/", websockethandler), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.ioloop.instance().start()
however, can't send messages before receives one. how send message actively? example, measures time , if didn't receive messages 10 sec, send "are sleeping?".
i want make chatbot using websocket. use tornado , websocket because know this, , interested if know of better methods use in regard.
you can add schedule tornado.ioloop.periodiccallback
, check if there has been activity or not based on time, following (i adapted code , this answer):
import tornado.web import tornado.websocket import tornado.ioloop import time class websockethandler(tornado.websocket.websockethandler): def simple_init(self): self.last = time.time() self.stop = false def open(self): self.simple_init() print("new client connected") self.write_message("you connected") self.loop = tornado.ioloop.periodiccallback(self.check_ten_seconds, 1000, io_loop=tornado.ioloop.ioloop.instance()) self.loop.start() def on_message(self, message): self.write_message(u"you said: " + message) self.last = time.time() def on_close(self): print("client disconnected") self.loop.stop() def check_origin(self, origin): return true def check_ten_seconds(self): print("just checking") if (time.time() - self.last > 10): self.write_message("you sleeping mate?") self.last = time.time()
now client alternating between idling , writing (adapted here):
class client(object): def __init__(self, url, timeout): self.url = url self.timeout = timeout self.ioloop = ioloop.instance() self.ws = none self.connect() periodiccallback(self.keep_alive, 20000, io_loop=self.ioloop).start() self.ioloop.start() @gen.coroutine def connect(self): print("trying connect") try: self.ws = yield websocket_connect(self.url) except exception e: print("connection error") else: print("connected") self.run() @gen.coroutine def run(self): once = false while true: msg = yield self.ws.read_message() print(msg) if once: time.sleep(11) once = false else: time.sleep(1) once = true self.ws.write_message("hello matey") if msg none: print("connection closed") self.ws = none break def keep_alive(self): if self.ws none: self.connect() else: self.ws.write_message("keep alive")
we obtain expected output:
trying connect connected connected said: hello matey sleeping mate? said: hello matey said: hello matey sleeping mate?
Comments
Post a Comment