延續『WebSocket 雙向即時通訊 - 初探』,今天就以 Tornado 來寫個簡單的 WebSocket 範例。當 client 連到 server 後,會傳送 hello ,而 server 回應一樣的訊息,傳送到第五次,server 就把 client 斷掉。
Server (ws_server.py)
import tornado.ioloop import tornado.web from tornado import websocket class WSHandler(websocket.WebSocketHandler): count = 0 def open(self): print "Client connected" def on_message(self, msg): print "[%d] Got message [%s] from client" % (self.count, msg) if self.count == 4: self.close() return # Write back message self.write_message("[%d] Echo: %s" % (self.count, msg)) self.count += 1 def on_close(self): print "Client disconnected" application = tornado.web.Application([ (r"/", WSHandler), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
Client (ws_client.py)
from tornado.websocket import websocket_connect from tornado.ioloop import IOLoop class ws_client(): conn = None # This is WebSocketClientConnection def __init__(self): websocket_connect('ws://localhost:8888/', callback=self.conn_cb) def conn_cb(self, future): self.conn = future.result() self.conn.write_message("hello") self.conn.read_message(self.read_cb) def read_cb(self, future): msg = future.result() if msg is None: print "Server disconnected" IOLoop.instance().stop() else: print msg self.conn.write_message("hello") self.conn.read_message(self.read_cb) if __name__ == '__main__': ws_client() IOLoop.instance().start()
沒有留言:
張貼留言