Currently I am trying to repeatedly connect and disconnect to a device (TCP socket). Here is the flow
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.
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.