Node.js中的net模块提供了对TCP协议的封装,使用net模块可以轻松的构建一个TCP服务器,或构建一个连接TCP服务器的客户端。
我们通过一个实例学习net模块,下面我们用net模块创建一个TCP服务进行通信,用telnet进行群聊:
const events = require('events');
const net = require('net');
const channel = new events.EventEmitter();
channel.clients = {};
channel.subscription = {};
channel.on('join', function(id, client) {
this.clients[id] = client;
this.subscription[id] = (senderId, message) => {
if (id != senderId) {
this.clients[id].write(id + ': ' + message);
}
};
this.clients[id].write(`当前已加入的人数${this.listeners('broadcast').length + 1}\n`);
this.on('broadcast', this.subscription[id]);
});
channel.on('leave', function(id) {
channel.removeListener(
'broadcast', this.subscription[id]
);
channel.emit('broadcast', id, `${id} has left the chatroom.\n`);
});
const server = net.createServer(client => {
const id = `${client.remoteAddress}:${client.remotePort}`;
console.log('有TCP客服端连接入');
channel.emit('join', id, client);
client.on('data', data => {
data = data.toString();
channel.emit('broadcast', id, data);
});
client.on('close', () => {
console.log('有人离开');
channel.emit('leave', id);
});
});
server.listen(8888, function() {
console.log('开启8888端口');
});
通过终端输入:
telnet localhost 8888
WechatIMG37.png
只要连接到localhost 8888
,我们可以开始聊天了。
网友评论