2013/04/23

WebSocket on Tornado

Tornado 一直是我愛用的 python web framework,這幾年工作上一直在寫 event-drivent socket programming,所以被它 non-blocking 的特性給深深吸引,如果每件 block 的工作都能用 asynchronous 的方式來解決,那程式執行的效率一定超好!


延續『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()


沒有留言:

張貼留言