Nodejs websocket入門

來源:互聯網
上載者:User

標籤:

websocket

2011年技術文檔

http://www.ibm.com/developerworks/cn/web/1112_huangxa_websocket/index.html

 

瀏覽器端介面:

https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API

 

WebSockets.org網站:http://www.websockets.org/

 

認識websocket

http://www.html5rocks.com/en/tutorials/websockets/basics/

http://javascript.ruanyifeng.com/htmlapi/websocket.html

HTTP協議是一種無狀態協議,伺服器端本身不具有識別用戶端的能力,必須藉助外部機制,比如session和cookie,才能與特定用戶端保持 對話。這多多少少帶來一些不便,尤其在伺服器端與用戶端需要持續交換資料的場合(比如網路聊天),更是如此。為瞭解決這個問題,HTML5提出了瀏覽器的WebSocket API。

WebSocket的主要作用是,允許伺服器端與用戶端進行全雙工系統(full-duplex)的通訊。舉例來說,HTTP協議有點像發電子郵件,發 出後必須等待對方回信;WebSocket則是像打電話,伺服器端和用戶端可以同時向對方發送資料,它們之間存著一條持續開啟的資料通道。

WebSocket協議完全可以取代Ajax方法,用來向伺服器端發送文本和位元據,而且還沒有“同域限制”。

nodejs Demo安裝

https://github.com/websockets/ws

來自

http://www.html5rocks.com/en/tutorials/websockets/basics/

Server Side Implementations
  • Node.js
    • Socket.IO
    • WebSocket-Node
    • ws

 

從 https://github.com/websockets/ws 下載以後, 解壓後到目標目錄, 執行

npm install --save ws

進行安裝。

遇到報錯 Refusing to install hapi as a dependency of itself:

http://stackoverflow.com/questions/27267707/npm-warn-install-refusing-to-install-hapi-as-a-dependency-of-itself

通過修改 package.json 中 name名稱解決。 例如 ws-test

 

到 example檔案夾下, 運行node server.js結果報錯:Cannot find module ‘xxx‘ 問題解決

通過如下方法解決:

http://blog.csdn.net/wmsjlihuan/article/details/19816389

Cannot find module ‘xxx‘ 問題解決

使用npm install -g ‘xxx‘ 之後仍然報 
Cannot find module ‘xxx‘ 錯誤,可以通過設定環境變數來解決; 

export NODE_PATH=/usr/local/lib/node_modules/  
echo $NODE_PATH  

 

運行結果

[email protected]:/home/share/ws-master/ws-master/examples/serverstats$ node server.js

started client interval
stopping client interval
started client interval
stopping client interval

 

頁面不斷重新整理資料,很快! 這些內容都是由後台間隔200ms推送到前台。

 

代碼如下:

server

var WebSocketServer = require(‘../../‘).Server  , http = require(‘http‘)  , express = require(‘express‘)  , app = express.createServer();app.use(express.static(__dirname + ‘/public‘));app.listen(8080);var wss = new WebSocketServer({server: app});wss.on(‘connection‘, function(ws) {  var id = setInterval(function() {    ws.send(JSON.stringify(process.memoryUsage()), function() { /* ignore errors */ });  }, 100);  console.log(‘started client interval‘);  ws.on(‘close‘, function() {    console.log(‘stopping client interval‘);    clearInterval(id);  });});

 

client

<!DOCTYPE html><html>  <head>    <style>      body {        font-family: Tahoma, Geneva, sans-serif;      }      div {        display: inline;      }    </style>    <script>      function updateStats(memuse) {        document.getElementById(‘rss‘).innerHTML = memuse.rss;        document.getElementById(‘heapTotal‘).innerHTML = memuse.heapTotal;        document.getElementById(‘heapUsed‘).innerHTML = memuse.heapUsed;      }      var host = window.document.location.host.replace(/:.*/, ‘‘);      var ws = new WebSocket(‘ws://‘ + host + ‘:8080‘);      ws.onmessage = function (event) {        updateStats(JSON.parse(event.data));      };    </script>  </head>  <body>    <strong>Server Stats</strong><br>    RSS: <div id=‘rss‘></div><br>    Heap total: <div id=‘heapTotal‘></div><br>    Heap used: <div id=‘heapUsed‘></div><br>  </body></html>

 

評價

websocket屬於新事物, 瀏覽器支援度有差異。

如果考慮老舊瀏覽器,可以使用開源commet架構, pushlet:

http://www.ibm.com/developerworks/cn/web/wa-lo-comet/index.html

 

對於只需要伺服器推送訊息的情況, 可以使用SSE

http://server.ctocio.com.cn/181/13158181.shtml

http://www.html5rocks.com/en/tutorials/eventsource/basics/

Nodejs websocket入門

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.