Node.js 是一個(gè)基于Chrome JavaScript運(yùn)行時(shí)建立的一個(gè)平臺(tái), 用來(lái)方便地搭建快速的,易于擴(kuò)展的網(wǎng)絡(luò)應(yīng)用,今天我們來(lái)探討下,如何使用node.js實(shí)現(xiàn)簡(jiǎn)單的聊天服務(wù)器
使用Nodejs是如此簡(jiǎn)單的實(shí)現(xiàn)了一個(gè)簡(jiǎn)單的聊天服務(wù)器
實(shí)現(xiàn)代碼如下:
var net = require('net');
var chatServer = net.createServer(),clientList = [];
chatServer.on("connection",function(client){
client.name = client.remoteAddress + ":" + client.remotePort;
client.write("Hi! "+client.name+" \n");
clientList.push(client);
client.on("data",function(data){
//數(shù)據(jù)發(fā)送給客戶端
broadcast(data,client);
// clientList[i].write(data);
});
client.on("end",function(){
clientList.splice(clientList.indexOf(client),1);
});
client.on("error",function(e){
console.log(e)
});
});
chatServer.listen(9000)
function broadcast(message,client){
var cleanup = [];
for(var i=0;i<clientList.length;i++){
if(client != clientList[i]){
if(clientList[i].writable){
clientList[i].write(client.name = "says:"+message);
}else{
cleanup.push[clientList[i]];
clientList[i].destory();
}
}
}
}使用過(guò)程就是:
啟動(dòng)js
node chat.js連接方式:telnet
telnet 127.0.0.1 9000
更多信息請(qǐng)查看IT技術(shù)專欄