参考资料:
http://cnodejs.org/topic/4f32142e69bab4d67601bd1b
http://www.oschina.net/question/12_54009
在使用socket.io之前,我按照网上的各种成功的例子,尝试使用node-websocket-server库实现WebSocket.
我先从https://github.com/miksago/node-websocket-server下载的node-websocket-server. 然后使用Chrome24浏览器,通过WebSocket对象发送请求,结果服务器端识别成draft75,并且报process.studo.flush函数不存在等异常.网上说是库的版本过低,无法识别新的WebSocket标准.
估计网上的那些例子都是基于低版本的浏览器和node-websocket-server库实现的,于是我放弃node-websocket-server库,改用socket.io库.
1. 下载和安装Node.js
下载地址:http://nodejs.org/dist/v0.8.20/node-v0.8.20-x86.msi
下载之后在本地执行安装.
2. 安装socket.io
我使用Eclipse创建的工程的目录结构:
-----------------------------------------------
-----------------------------------------------
打开CMD,跳转到WebContent目录下,执行命令: npm install socket.io
等待,直到安装完毕,返回CMD输入状态.
安装完成的secket.io库的目录结构:
-----------------------------------------------
-----------------------------------------------
-----------------------------------------------
3. 创建服务器端代码Server.js
var fs = require('fs'), http = require('http'), socketio = require('socket.io'); var server = http.createServer(function(req, res) { res.writeHead(200, { 'Content-type': 'text/html'}); res.end(fs.readFileSync(__dirname + '/index.html')); }).listen(8080, function() { console.log('Listening at: http://localhost:8080'); }); socketio.listen(server).on('connection', function (socket) { socket.on('message', function (msg) { console.log('Message Received: ', msg); socket.broadcast.emit('message', msg); }); });
4. 创建客户端代码index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="jquery-1.8.2.js"></script> <!-- 这里要引用secket.io客户端文件 --> <script type="text/javascript" src="node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js"></script> <script type="text/javascript" src="Client.js"></script> </head> <body> <div> Incoming Chat: <ul id="incomingChatMessages"></ul> <br/> <input type="text" id="outgoingChatMessage"> <button id="openConnect">Send Message</button> </div> </body> </html>
5. 创建客户端代码Client.js
$(document).ready(function(){ var iosocket = io.connect("http://localhost:8080"); iosocket.on('connect', function () { $('#incomingChatMessages').append($('<li>Connected</li>')); iosocket.on('message', function(message) { $('#incomingChatMessages').append($('<li></li>').text(message)); }); iosocket.on('disconnect', function() { $('#incomingChatMessages').append('<li>Disconnected</li>'); }); }); $("#openConnect").click(function(event){ openConnect(iosocket); }); }); function openConnect(iosocket){ iosocket.send($('#outgoingChatMessage').val()); $('#incomingChatMessages').append($('<li></li>').text($('#outgoingChatMessage').val())); $('#outgoingChatMessage').val(''); }
6. 测试
在CMD中,跳转到WebContent目录,执行命令: node Server.js
在浏览器中打开index.html页面,输入信息,点击"Send Message"按钮.