用NodeJS创建一个聊天服务器

时间:2022-02-11 00:52:48

Node 是专注于创建网络应用的,网络应用就需要许多I/O(输入/输出)操作。让我们用Node实现有多么简单,并且还能轻松扩展。

创建一个TCP服务器

var net = require('net');
var chatServer = net.createServer(); chatServer.on("connection", function(client) {
client.write('Hi!\n');
client.on('data', function(data) {
console.log(data); }); });
chatServer.listen(9000);

用NodeJS创建一个聊天服务器

我们用Telnet 连接上localhost:9000,向服务器发送hi,Node显示出一堆二进制的数据,原来Javascript无法很好的处理的二进制数据,所以引入Buffer库来处理。

客户端互相发送消息

var net = require('net');
var chatServer = net.createServer();
clientList = [];
chatServer.on("connection", function(client) {
client.write('Hi!\n');
client.name = client.remoteAddress + ":" + client.remotePort;
client.write('Hi' + client.name + '\n');
clientList.push(client);
client.on('data', function(data) {
broadcast(data, client);
}); }); function broadcast(msg, client) {
for (var i = 0, clen = clientList.length; i < clen; i++) {
if (client !== clientList[i]) {
clientList[i].write(client.name + " says " + msg + "\n");
} }
}
chatServer.listen(9000);

用NodeJS创建一个聊天服务器

当我们断开其中的一个客户端的话,服务器会报如下错误:

用NodeJS创建一个聊天服务器

检查socket可写状态将程序变得更健壮

var net = require('net');
var chatServer = net.createServer();
clientList = [];
chatServer.on("connection", function(client) {
client.write('Hi!\n');
client.name = client.remoteAddress + ":" + client.remotePort;
client.write('Hi' + client.name + '\n');
clientList.push(client);
client.on('data', function(data) {
broadcast(data, client);
});
//客户端退出
client.on('end', function() {
console.log(client.name + " quit");
clientList.splice(clientList.indexOf(client), 1);
}); }); function broadcast(msg, client) {
var cleanup = [];
for (var i = 0, clen = clientList.length; i < clen; i++) {
if (client !== clientList[i]) {
//检查socket是否可写
if (clientList[i].writable) {
clientList[i].write(client.name + " says " + msg + "\n");
} else {
cleanup.push(clientList[i]);
clientList[i].destroy(); //对断开连接的socket进行销毁
}
}
}
//在写入循环中删除死节点,消除垃圾索引
for (var i = 0, clenuplen = cleanup.length; i < clenuplen; i++) {
clientList.splice(clientList.indexOf(cleanup[i]), 1);
}
}
chatServer.listen(9000);

记录错误日志

 //记录错误日志
client.on('error', function(e) {
console.log(e);
})

为client对象添加error事件后,客户端发生的任何错误都会被记录下来。