上一篇文章: Python:Tornado 第三章:HTML5 WebSocket概念及應用:第一節:WebSocket概念
下一篇文章: Python:Tornado 第三章:HTML5 WebSocket概念及應用:第三節:客戶端編程
Tornado定義了tornado.websocket.WebSocketHandler類用於處理WebSocket連接的請求,應用開發者應該繼承該類並實現其中的open()、on_message()、on_close()函數。html
除了這三個Tornado框架自動調用的入口函數,WebSocketHandler還提供了兩個開發者主動操做WebSocket函數。node
下面是持續爲客戶端推送時間消息的Tornado WebSocket程序:web
import tornado.ioloop import tornado.web import tornado.websocket from tornado import gen from tornado.options import define,options,parse_command_line import asyncio clients=dict()#客戶端Session字典 class IndexHandler(tornado.web.RequestHandler): @tornado.web.asynchronous @gen.coroutine def get(self): print("123") self.render("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}#保存Session到clients字典中 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 class SendThread(threading.Thread): # 啓動單獨的線程運行此函數,每隔1秒向全部的客戶端推送當前時間 def run(self): # tornado 5 中引入asyncio.set_event_loop,否則會報錯 asyncio.set_event_loop(asyncio.new_event_loop()) 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__': #啓動推送時間線程 SendThread().start() parse_command_line() app.listen(8888) #掛起運行 tornado.ioloop.IOLoop.instance().start()
解析上述代碼以下:編程