WebSocket-SockJS

一、什么是SockJS

SockJS是一个JavaScript库,提供跨浏览器JavaScript的API,创建了一个低延迟、全双工的浏览器和web服务器之间通信通道。
服务端:sockjs-node(https://github.com/sockjs/sockjs-node)
客户端:sockjs-clien(https://github.com/sockjs/sockjs-client)
node-static(https://www.npmjs.com/package/node-static)是Node.js兼容HTTP静态文件服务器处理模块,提供内置的缓存支持。

二、实例

1. package.json(依赖)

{
	"name":"sockjsDemo",
	"version":"0.0.1",
	"dependencies":{
		"node-static":"0.5.9",
		"sockjs":"*"
	}
}

2. server.js(服务端)

/* 第1步:引入所需模块【http模块、sockjs模块、静态文件服务器处理模块】*/
var http = require('http');
var sockjs = require('sockjs');
var node_static = require('node-static');

/* 第2步:创建sockjs服务 */
var sockjs_opts = {sockjs_url:"http://cdn.jsdelivr.net/sockjs/1.0.1/sockjs.min.js"};
var sockjs_server = sockjs.createServer(sockjs_opts);
sockjs_server.on('connection',function(conn){
	conn.on('data',function(message){
		conn.write('我就不告诉你' + message);
	});
});

/* 第3步:指定静态服务文件目录 */
var static_directory = new node_static.Server(__dirname);

/* 第4步:传递http请求和响应给指定目录 */
var server = http.createServer();
server.addListener('request', function(req, res) {
    static_directory.serve(req, res);
});
server.addListener('upgrade', function(req, res){
    res.end();
});

/* 第5步:将sockjs服务挂载到http服务上 */
sockjs_server.installHandlers(server,{prefix:'/sockjsDemo'});

/* 第6步:指定监听端口和地址 */
console.log(' [*] Listening on 0.0.0.0:10086' );
server.listen(10086, '127.0.0.1');

3. index.html(客户端)

<!doctype html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script src="http://cdn.jsdelivr.net/sockjs/1.0.1/sockjs.min.js"></script>
    <style>
      .box {
          width: 300px;
          float: left;
          margin: 0 20px 0 20px;
      }
      .box div, .box input {
          border: 1px solid;
          -moz-border-radius: 4px;
          border-radius: 4px;
          width: 100%;
          padding: 0px;
          margin: 5px;
      }
      .box div {
          border-color: grey;
          height: 300px;
          overflow: auto;
      }
      .box input {
          height: 30px;
      }
      h1 {
          margin-left: 30px;
      }
      body {
          background-color: #F0F0F0;
          font-family: "Arial";
      }
    </style>
</head>
<body lang="en">
    <h1>Index</h1>
    <div id="first" class="box">
      <div></div>
      <form><input autocomplete="off" value="Type here..."></input></form>
    </div>
    <script>
        var sockjs_url = '/sockjsDemo';
        var sockjs = new SockJS(sockjs_url);
        $('#first input').focus();

        var div  = $('#first div');
        var inp  = $('#first input');
        var form = $('#first form');

        var print = function(m, p) {
            p = (p === undefined) ? '' : JSON.stringify(p);
            div.append($("<code>").text(m + ' ' + p));
            div.append($("<br>"));
            div.scrollTop(div.scrollTop()+10000);
        };

        sockjs.onopen    = function()  {print('[*] open', sockjs.protocol);};
        sockjs.onmessage = function(e) {print('[.] message', e.data);};
        sockjs.onclose   = function()  {print('[*] close');};

        form.submit(function() {
            print('[ ] sending', inp.val());
            sockjs.send(inp.val());
            inp.val('');
            return false;
        });
    </script>
</body>
</html>
[转载请标明出处: http://blog.csdn.net/ligang2585116 ]

你可能感兴趣的:(websocket,sockjs,sockjs-node,sockjs-clien)