websocket 服務端(tornado)
阿新 • • 發佈:2018-11-14
import tornado.ioloop import tornado.web import tornado.websocket from tornado.options import define, options, parse_command_line from tornado import gen define("port", default=9993, help="run on the port", type=int) clients = dict() class IndexHandler(tornado.web.RequestHandler): @tornado.gen.coroutine def get(self): self.write("<h1>IndexHandler calling</h1>") self.render("xxx.html") #html可以包含websocket客戶端實現連結 class MyWebsocketHandler(tornado.websocket.WebSocketHandler): @tornado.gen.coroutine def get(self): #路由顯示 self.write("<h1>waiting for clients conenct!</h1>") def open(self, *args): #新連結呼叫 slef.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 True app = tornado.web.Application([(r'/',IndexHandler),(r'/websocket', MyWebsocketHandler),]) #雙路由 import threading import time def send_time(): #向所有的客戶端傳送當前時間 import datetime while True: for key in clients.keys(): msg = str(datetime.datetime.now()) clients[key]["object"].write_message(msg) print("write to cleint %s : %s"%(key, msg)) time.sleep(1) if __name__ == "__main__": threading.Thread(target=send_time).start() #啟動當前執行緒推送時間 parse_command_line() app.listen(options.port) tornado.ioloop.IOLoop.instance().start()#掛起執行
tornado自己提供的websocket庫以外,也可以自己構建websocket伺服器!部落格中有!