3

I'm building a tcp-message server with nodejs. It just sits on my server waiting to accept a connection from lets say an Arduino.

As it, at connection-time, identifies itself with an unique ID (not an IP) I'm able to write data from server > arduino without knowing the IP address of the client-device.

But for that to be efficient, I want the connection to be open as long as possible, preferably as long as the client-device closes the connection. (eg on ip change or something)

This is the (relevant part of) the server:

var net = require('net'),
sockets = {};

var tcp = net.createServer(function(soc){
    soc.setKeepAlive(true); //- 1

    soc.on('connect', function(data){
       soc.setKeepAlive(true); //- 2
    });

    soc.on('data', function(data) {
      //- do stuff with the data, and after identification
      //  store in sockets{}

    })
}).listen(1111);

Is soc.setKeepAlive(true) the right method to keep the connection alive? If so, what is the right place to put it? In the connect event (1), or right in the callback (2).

If this is not the way to do it, what is?

1
  • socket.setKeepAlive(true) only enables TCP keepalive. It's a bit of misnomer because it actually detects broken connections and closes them. It doesn't do anything to make connections stay open longer than they otherwise would. Commented Sep 25, 2017 at 12:45

1 Answer 1

4

Your best bet is to periodically send your own heartbeat messages.

Also, you don't need soc.on('connect', ...) because the client socket is already connected when that callback is executed.

Sign up to request clarification or add additional context in comments.

3 Comments

O.k. a heartbeat it is then. What interval do you suggest? Does a heartbeat need to be a character? Or could it also be something different then data?
It can be whatever interval you feel is necessary for your application. The actual payload doesn't matter, as long as you can uniquely and easily identify it on the other side.
@mscdex Hi I need to connect to tcp server I am having host and port for the server. Can I use some module other then net to connect?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.