集成node.js中的websocket,只須要執行命令npm install nodejs-websocket便可
服務器端代碼以下:
var ws = require('nodejs-websocket');
//var connection = require('connection');
var conns = new Array();
console.log('開始創建鏈接。。。。');
var server = ws.createServer(function(conn){
conn.on('text',function(str){
var data = JSON.parse(str);
var type = data.type;
console.log(type);
switch(type){
case 1:
console.log("登陸!");
conns.push(conn);
conn.sendText(data.username+"\t登陸成功!");
break;
case 2:
console.log("發送信息:"+data.message);
for(var i = 0;i < conns.length;i++){
conns[i].sendText(data.username+"說:"+data.message);
}
break;
default:
break;
}
});
conn.on('close',function(code,reason){
console.log("關閉鏈接");
});
conn.on('error',function(code,reason){
console.log('異常關閉');
});
});
server.listen(8001);
console.log('Websocket創建完畢');