Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
719 views
in Technique[技术] by (71.8m points)

node.js - How to use setKeepAlive to disconnect TCP server when client is gone in NodeJS

New to NodeJS. How do I useKeepAlive to detect for connection break in my TCP server when my client disengage or break off contact. I need to prevent my Nodejs from sending messages(not shown here) after getting messages from other server

The following is the error message I gotten

{ Error: This socket has been ended by the other party
    at Socket.writeAfterFIN [as write] (net.js:401:12)
    at Timeout._onTimeout (/home/agcas/development/aerosense.demo/sigfox/app.js:278:36)
    at ontimeout (timers.js:427:11)
    at tryOnTimeout (timers.js:289:5)
    at listOnTimeout (timers.js:252:5)
    at Timer.processTimers (timers.js:212:10) code: 'EPIPE' }

This is my code

var tcpserver = net.createServer(function(socket) {

     socket.setKeepAlive(true, 600); //1 min = 60000 milliseconds.

    // Track the client
    clients.push(socket);

    socket.write('Echo server
');
 
    socket.write('......
');  
    socket.write('Connected with the server 
');
    socket.write('Waiting for communication
');

    socket.on('error', function(err) {
       console.log(err)
    });
});



tcpserver.on('connection',function(socket){
     console.log('Detected connection with the client');

     var rport = socket.remotePort;
     var raddr = socket.remoteAddress;
     var rfamily = socket.remoteFamily;

     console.log('REMOTE Socket is listening at port:' + rport);
     console.log('REMOTE Socket ip :' + raddr);
     console.log('REMOTE Socket is IP4/IP6 : ' + rfamily);

});


tcpserver.listen(config.tcp_port, config.host, function(){
    var host   = tcpserver.address().address
    var portid = tcpserver.address().port

    console.log('TCP server listening at http://%s:%s', host, portid);
    console.log("TCP server listening on port " + portid);
});

Do I have to use something like tcpserver.disconnect? Or I have to block the send function?

Thanks for your help

question from:https://stackoverflow.com/questions/65888314/how-to-use-setkeepalive-to-disconnect-tcp-server-when-client-is-gone-in-nodejs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...