1.导入模块,监听端口
var net = require('net');
//创建服务器
var server = net.createServer(8081);
2.接受客户端连接
//监听连接事件
server.on('connection', function (socket) {
socket.write("you have connected the server,input 'q' to quit\n");
sockets.push(socket);
console.log(sockets.length + ' have connected');
});
3.从连接中读取数据
//创建集合管理socket
var sockets = [];
//socket监听数据
socket.on('data', function (data) {
//如果监听到的数据是'q',则断开socket连接
if (data.toString().trim().toLowerCase() === 'q') {
socket.write('you have quited the chat room\n');
return socket.end();
}
//将socket传输的数据广播到其他socket
sockets.forEach(function (otherSocket) {
//排除掉发送数据的socket
if (otherSocket !== socket) {
otherSocket.write(data.toString());
}
})
});
//socket连接断开后从sockets中移除socket
socket.on('end', function () {
console.log('a client have quited the chat room\n');
sockets.splice(sockets.indexOf(socket), 1);
console.log(sockets.length + ' have connected');
});
效果
1.通过node server.js启动
服务端
2.通过telnet localhost 8081
分别启动客户端1和客户端2
客户端:
服务端:
3.两个客户端相互通信,客户端1发送hello,客户端2发送world
截图中客户端1的hello是发送出去的,world是收到的数据
4.客户端输入’q’退出
客户端:
服务器端:
完整代码
server.js
var net = require('net');
//创建集合管理socket
var sockets = [];
//创建服务器
var server = net.createServer().listen(8081);
//监听连接事件
server.on('connection', function (socket) {
socket.write("you have connected the server,input 'q' to quit\n");
//将socket放入sockets集合
sockets.push(socket);
console.log(sockets.length + ' have connected');
//socket监听数据
socket.on('data', function (data) {
//如果监听到的数据是'q',则断开socket连接
if (data.toString().trim().toLowerCase() === 'q') {
socket.write('you have quited the chat room\n');
return socket.end();
}
//将socket传输的数据广播到其他socket
sockets.forEach(function (otherSocket) {
//排除掉发送数据的socket
if (otherSocket !== socket) {
otherSocket.write(data.toString());
}
})
});
//socket连接断开后从sockets中移除socket
socket.on('end', function () {
console.log('a client have quited the chat room\n');
sockets.splice(sockets.indexOf(socket), 1);
console.log(sockets.length + ' have connected');
});
});