Just starting out in node.js programming and writing a tcp socket client.
I want the client to connect to a server. If the server is not available (i.e. server does not exist at a agreed port), i want the client to timeout and reconnect after the timeout.
I have this code but it hangs at the second client.connect. What's wrong?
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 9000;
var client = new net.Socket();
client.connect(PORT, HOST, function(){
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('I am Superman!');
});
client.on('error', function(e) {
while (e.code == 'ECONNREFUSED') {
console.log('Is the server running at ' + PORT + '?');`
socket.setTimeout(1000, function() {
console.log('Timeout for 5 seconds before trying port:' + PORT + ' again');
}
client.connect(PORT, HOST, function(){
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('I am the inner superman');
});
});
});
Updated code:
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 9000;
var client = new net.Socket();
client.connect(PORT, HOST, function(){
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('I am Superman');
});
client.on('error', function(e) {
while (e.code == 'ECONNREFUSED') {
console.log('Is the server running at ' + PORT + '?');
client.setTimeout(4000, function() {
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('I am inner Superman');
});
console.log('Timeout for 5 seconds before trying port:' + PORT + ' again');
});
}
});
client.on('data', function(data) {
console.log('DATA: ' + data);
client.destroy();
});
client.on('close', function() {
console.log('Connection closed');
});
With the updated code, the timeout does not appear to take effect. When i start this client with no corresponding server, the result shows below with no 4 second wait.
Is the server running at 9000?
Is the server running at 9000?
Is the server running at 9000?
Is the server running at 9000?
…
Update (Barking up the wrong tree?)
I went back to look at the socket.on('error') event and saw that the close event is called immediately after the error. So the code will close out the tcpclient without waiting for 4 seconds. Any better ideas?
You're timeout is reversed.
Should look like:
The function you want to run after the timeout is the callback. That's the one that waits for execution.
Also, change your
while
to anif
, that condition won't change during a single error event. And your parens and brackets are mismatched.per my comment on accepted answer I discovered an issue using the
.connect
callback vs the'connect'
listener. Each time you call .connect it cues the callback (adds a listener) even though the connection fails. So when it finally does connect all those callbacks get called. So if you use.once('connect'..
instead that won't happen. Below are logging statements from my project's client code that led me to this observation.so try this version below instead