Stay Hungry,Stay Foolish!

Nodejs websocket入门

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

 

从 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  

 

运行结果

fqs@fqs:/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/

posted @ 2016-09-17 23:36  lightsong  阅读(2379)  评论(0编辑  收藏  举报
Life Is Short, We Need Ship To Travel