WebSocket使用初探(Tornado+Nginx)

使用場(chǎng)景

在web開發(fā)中有時(shí)候需要實(shí)時(shí)獲取數(shù)據(jù),可以采用的方法也很多,比如ajax輪詢,長(zhǎng)連接等。之前項(xiàng)目中有一個(gè)需求是實(shí)時(shí)的日志展示,實(shí)時(shí)性要求高
還有根據(jù)歷史監(jiān)控?cái)?shù)據(jù)進(jìn)行趨勢(shì)圖的繪制,數(shù)據(jù)量巨大,等待時(shí)間長(zhǎng)。那么如果使用http請(qǐng)求來處理則面臨著超時(shí)的問題,如果用ajax頻繁的輪詢將對(duì)服務(wù)器造成很大的壓力。websocket提供了客戶端和服務(wù)器進(jìn)行雙向?qū)崟r(shí)的全雙工通信的方法。并且絕大多數(shù)現(xiàn)代瀏覽器都支持websocket,因此需要使用nginx對(duì)websocket服務(wù)進(jìn)行反代和負(fù)載均衡,nginx從1.3版本后開始支持websocket。項(xiàng)目用到的tornado框架也原生支持websocket,看來可以嘗試用websocket來嘗試解決問題。

Tornado的支持

tornado對(duì)websocket支持的很好,通過繼承tornado.websocket.WebSocketHandler類就可以實(shí)現(xiàn)對(duì)websocket連接的處理。websocket是在標(biāo)準(zhǔn)
http上實(shí)現(xiàn)的,websocket中的握手和http中的握手兼容,它使用http中的Upgrade協(xié)議頭將連接從http升級(jí)到WebSocket,從源碼上可以看出
WebSocketHandler繼承了tornado.web.RequestHandler,因此websocket也可以通過get_argument方法獲取ws://URL?**=傳來的參數(shù)。
WebSocketHandler提供了一系列方法用以處理連接和消息收發(fā),源碼中的docstring描述得很清楚,源碼是最好的文檔沒有之一。

class WebSocketHandler(tornado.web.RequestHandler):
"""Subclass this class to create a basic WebSocket handler.

Override `on_message` to handle incoming messages, and use
`write_message` to send messages to the client. You can also
override `open` and `on_close` to handle opened and closed
connections.

See http://dev.w3.org/html5/websockets/ for details on the
JavaScript interface.  The protocol is specified at
http://tools.ietf.org/html/rfc6455.

Here is an example WebSocket handler that echos back all received messages
back to the client:

.. testcode::

  class EchoWebSocket(tornado.websocket.WebSocketHandler):
      def open(self):
          print("WebSocket opened")

      def on_message(self, message):
          self.write_message(u"You said: " + message)

      def on_close(self):
          print("WebSocket closed")

.. testoutput::
   :hide:

...

Nginx配置反向代理和負(fù)載均衡

upstream tornadoes {
    server 127.0.0.1:7000;
    server 127.0.0.1:7001;
}

server {
    listen 8000;
    server_name ***.com;

    location / {
        proxy_pass http://tornadoes;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
    }
}

nginx默認(rèn)采用循環(huán)的方式分配請(qǐng)求,循環(huán)的將請(qǐng)求分配到upstream中定義的服務(wù)地址。location中的定義對(duì)支持websocket必不可少。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容