标签:websocket websocket-sockjs sockjs-node sockjs-clien sockjs
{ "name":"sockjsDemo", "version":"0.0.1", "dependencies":{ "node-static":"0.5.9", "sockjs":"*" } }
/* 第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');
<!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]
版权声明:本文为博主原创文章,未经博主允许不得转载。转载请标明出处:http://blog.csdn.net/ligang2585116!
标签:websocket websocket-sockjs sockjs-node sockjs-clien sockjs
原文地址:http://blog.csdn.net/ligang2585116/article/details/47277917