服务端代码
var net = require('net');
var port = 4002;
var sockets = [];
var server = net.createServer();
server.on('listening', function() {
console.log('Tcp is listening on port ' + port + '.');
});
server.on('connection', function(socket) {
console.log('Server has a new connection.');
sockets.push(socket);
socket.on('data', function(buffer) {
if (buffer.toString() === "close\r\n") {
socket.end();
// server.close();
}
sockets.forEach(function(other_socket) {
if (other_socket !== socket) {
other_socket.write(buffer);
}
});
});
socket.on('end', function(data) {
console.log('Socket is now closed.');
var index = sockets.indexOf(socket);
sockets.splice(index, 1);
});
socket.write('some thing');
});
server.on('close', function() {
console.log('Server is now closed.');
});
server.on('error', function(err) {
console.error(err);
});
server.listen(port);
客户端直接telnet 127.0.0.1 4002即可