最近在学习nodejs,参考的书籍为《NODE即学即用》,体会了一把传说中的node.js,感觉还可以的。
实验的是在ubuntu下完成的,需要提前安装好node.js和npm.需要具备一定的javascript基础。
其主要的代码如下:
const net = require('net');
const chatServer = net.createServer();
// 定义客户列表
var clientList = [];
chatServer.on('connection',function (client) {
// 提示连接成功
client.write('连接服务器成功...\n');
// 放到客户列表中
clientList.push(client);
// 监听到来自客户端发送的消息
client.on('data',function (data) {
client.name = client.remoteAddress+":"+client.remotePort;
broadcast(data,client);
});
// 监听断开时候,关闭端口
client.on('end',function() {
clientList.splice(clientList.indexOf(client),1);
});
client.on('error',function(e) {
console.log(e);
});
});
chatServer.listen(9000);
console.log("tcp 服务器链接已经建立...");
// 定义广播的方法
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+" 说 "+message);
}else{
cleanup.push(clientList[i]);
clientList[i].destory();
}
}
}
// 删除死节点
for(var i = 0;i<cleanup.length;i++){
clientList.splice(clientList.indexOf(cleanup[i]),1);
}
}
客户端A:
客户端B: