为什么 Node js tcp 服务器没有检测到断开连接的客户端

Why Node js tcp server not detecting disconnected client

我正在尝试在节点 js 中使用 TCP-IP 进行服务器-客户端通信

下面是我的服务器端代码,我有一个 GSM 设备充当 client.When GSM 设备连接到服务器 我收到设备已连接的消息!但是当我切断 GSM 设备的电源时,服务器应该会识别出设备已断开连接,但即使我有断开连接事件的代码,屏幕上也不会显示任何消息。

服务器代码

// Load the TCP Library
net = require('net');

// Keep track of the chat clients
var clients = [];

// Start a TCP Server
net.createServer(function (socket) {

// Identify this client
socket.name = socket.remoteAddress + ":" + socket.remotePort 

 // Put this new client in the list
 clients.push(socket);

 // Send a nice welcome message and announce
 socket.write("Welcome " + socket.name + "\n");
 broadcast(socket.name + " Device is connected!\n", socket);

 // Handle incoming messages from clients.
 socket.on('data', function (data) {
 broadcast(socket.name + "> " + data, socket);
 });

 // Remove the client from the list when it leaves
 socket.on('end', function () {
 clients.splice(clients.indexOf(socket), 1);
 broadcast(socket.name + " Device left.\n");
 });

 // Send a message to all clients
 function broadcast(message, sender) {
 clients.forEach(function (client) {
  // Don't want to send it to sender
  if (client === sender) return;
  client.write(message);
  });
  // Log it to the server output too
  process.stdout.write(message)
  }

  }).listen(5000);

  // Put a friendly message on the terminal of the server.
  console.log("Chat server running at port 5000\n");
// Load the TCP Library
net = require('net');

// Keep track of the chat clients
var clients = [];

// Start a TCP Server
net.createServer(function(socket) {
try {
    socket.setKeepAlive(true, 600); //1 min = 60000 milliseconds.
} catch (exception) {
    console.log('exception', exception);
}
socket.on('error', onError.bind({}, socket));

function onError(socket) {

    //console.log('Socket error!', socket);
    console.log('name', socket.name);


}
// Identify this client
socket.name = socket.remoteAddress + ":" + socket.remotePort

// Put this new client in the list
clients.push(socket);

// Send a nice welcome message and announce
socket.write("Welcome " + socket.name + "\n");
broadcast(socket.name + " joined\n", socket);

// Handle incoming messages from clients.
socket.on('data', function(data) {
    console.log(data);
    broadcast(socket.name + "> " + data, socket);
});

// Remove the client from the list when it leaves
socket.on('end', function() {
    clients.splice(clients.indexOf(socket), 1);
    broadcast(socket.name + " left .\n");
});

// Send a message to all clients
function broadcast(message, sender) {
    clients.forEach(function(client) {
        // Don't want to send it to sender
        if (client === sender) return;
        client.write(message);
    });
    // Log it to the server output too
    process.stdout.write(message)
   }

}).listen(8003);

 // Put a friendly message on the terminal of the server.
 console.log("Chat server running at port 8003\n");