顯示具有 WebSocket 標籤的文章。 顯示所有文章
顯示具有 WebSocket 標籤的文章。 顯示所有文章

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()

2013/04/13

WebSocket 雙向即時通訊 - 初探

Web 已經走向 Application 的概念,其中即時性(real-time)這個特點扮演很重要的角色

早期 Web service 要做到即時通訊不外乎兩種
  • Polling
    每n秒問一次 server,n 越小即時性越好,但相對 server loading 就越大
  • Long polling
    需要 Server support,延遲 response,確切來說是需要的時候再 response


但這兩種方式都需要額外的 overhead
  • HTTP 協定限制,一個 request 配一個 response,然後結束 connection,每次重新連線都需要 tcp 3-way handshake
  • Request 只能從 client 主動發出,若要做到 server push,client 得先建立一條連線讓 server 需要時 send back
  • 每次連線都要帶上 HTTP header,對頻寬也是一種浪費
  • Connection 斷掉再建立有個空窗期


而 WebSocket 正是改善這些缺點
  • 全雙工通訊(full-duplex communication),連線一旦建立,server/client 隨時都可以發送資料給對方
  • 除了第一次 handshake 外,過程中傳送資料的 header 很小
  • 避免對同一個網站建立多條 connection


WebSocket 的 implementation


WebSocket 對各種瀏覽器版本的支援度


WebSocket Protocol/Packet 分析


其實在 HTTP 1.0 與 1.1 也有 persistent connection 的實作
  • HTTP 1.0 persistent connection:又稱 HTTP keep-alive 或 HTTP connection reuse,可以在同個 connection 下發送多次 request/response 
  • HTTP 1.1 提出了 pipelining:允許一次發送多個 request 給 server,但 server response 時也必需按照順序
但這機制卻沒有被廣泛的應用?是因為早期的 web server 存在 C10K problem 嗎?還是 server 支援度的問題?加上 proxy 與 browser 有限制 client 到 web server 的 current connection 只能建立兩條,避免浪費 server 資源

詳細可以參考 HTTP 連線管理 | ihower { blogging }