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

时间:2017-07-11 11:04:57

标签: node.js sockets tcp tcp-ip

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

下面是我的服务器端代码,我有一个GSM设备充当客户端。当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");

1 个答案:

答案 0 :(得分:0)

// 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");