Python tornado websocker客户端编程(python编程)

网友投稿 338 2022-08-23


Python tornado websocker客户端编程(python编程)

Title Run WebSocker

#coding:utf-8import tornadofrom tornado.ioloop import IOLoopimport tornado.websocketimport tornado.webfrom tornado.options import define,options,parse_command_linedefine("port",default=8888,help="run on the given port",type=int)clients=dict()class IndexHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self, *args, **kwargs): self.render("../templates/index.html")class MyWebSocketHandler(tornado.websocket.WebSocketHandler): def open(self, *args, **kwargs): self.id=self.get_argument("id") self.stream.set_nodelay(True) clients[self.id]={"id":self.id,"object":self} def on_message(self, message): print("Client %s received a message %s "%(self.id,message)) def on_close(self): if self.id in clients: del clients[self.id] print("Client %s is closed "%self.id) def check_origin(self, origin): return Trueapp=tornado.web.Application(handlers=[ (r"/",IndexHandler), (r"/websocket",MyWebSocketHandler)],static_path="templates")import threadingimport timedef sendTime(): import datetime while True: for key in clients.keys(): msg=str(datetime.datetime.now()) clients[key]["object"].write_message(msg) print("write to client %s :%s"%(key,msg)) time.sleep(1)if __name__ == '__main__': threading.Thread(target=sendTime).start() parse_command_line() app.listen(options.port) IOLoop.instance().start()


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java的File类和IO流其实真的不难
下一篇:Python将图片的18k的大小变大(Python图片大小)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~