Search code examples
node.jsraw-sockets

Node.JS raw socket: how to do repeated connect-disconnect?


Currently I am trying to repeatedly connect and disconnect to a device (TCP socket). Here is the flow

  1. Connect to the device
  2. Send a "data".
  3. Have a delay of 200msec to ensure that the other end receives the data and it has already replied.
  4. Process the data
  5. Disconnect.
  6. Wait for 1 second
  7. Go back to 1.

This 1-time connection code is working (I got it from the web):

var net = require('net');
var HOST = '127.0.0.1';
var PORT = 23;

// (a) =========
var client = new net.Socket();
client.connect(PORT, HOST, function() {

    console.log('CONNECTED TO: ' + HOST + ':' + PORT);
    // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
    client.write('data');

});

// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {

    console.log('DATA: ' + data);
    // Close the client socket completely
    client.destroy();
});

// Add a 'close' event handler for the client socket
client.on('close', function() {
    console.log('Connection closed');
});

// (b) =========

Currently, the code above works for 1 time connection. I did put the code from (a) to (b) in a while(true) loops and placed a sleep of 1 second at the end using https://www.npmjs.com/package/sleep and it seems the connect isn't executing on that setup.

Any thoughts on this will be helpful.


Solution

  • I think the best way to do this, is to encapsule what you want to do in a function "loopConnection", and call recursively on each client.on('close') like this :

    var net = require('net');
    var HOST = '127.0.0.1';
    var PORT = 23;
    
    var loopConnection = function() {
        var client = new net.Socket();
    
        client.connect(PORT, HOST, function() {
            console.log('CONNECTED TO: ' + HOST + ':' + PORT);
            client.write('data');
        });
    
        client.on('data', function(data) {
            console.log('DATA: ' + data);
            client.destroy();
        });
    
        client.on('close', function() {
            console.log('Connection closed');
            setTimeout(function() {
                loopConnection(); // restart again
            }, 1000); // Wait for one second
        });
    };
    
    loopConnection(); // Initialize and first call loopConnection
    

    Hope it helps.