How can I gracefully handle a failed tcpSocket.connect attempt? - node.js

The following code causes an error when there is no existing TCP server to communicate with on the specified host:
const net = require('net');
const argv = require('minimist')(process.argv.slice(2));
try {
var tcpSocket = new net.Socket();
tcpSocket.connect(argv.tcpport, argv.tcphost, function onConnected() {
console.log('connected');
tcpSocket.on('data', function onIncoming(data) {
console.log(data);
});
tcpSocket.on('close', function onClose(data) {
tcpSocketConnected = false;
});
tcpSocketConnected = true;
});
} catch (err) {
console.log("PRINT ME: ", err);
}
Error:
events.js:183
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED 127.0.0.1:1906
at Object._errnoException (util.js:992:11)
at _exceptionWithHostPort (util.js:1014:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1186:14)
I am unable to catch the error even though I wrap the code in a try...catch.
Why does my catch block not catch the error?
How can I gracefully handle the error?

You should be able to explicitly handle the error event using event emitter api (same way as you handled close and data):
tcpSocket.on('error', handleError)
From Docs:
Event: 'error'#
Added in: v0.1.90
<Error>
Emitted when an error occurs. Unlike net.Socket, the 'close' event
will not be emitted directly following this event unless server.close()
is manually called. See the example in discussion of server.listen().

Related

Using setInterval with socket.write

This is the code that works but it writes the data just once:
var net = require('net');
var PORT = 3000;
var client = new net.Socket();
client.connect(PORT, function(){
client.write('{printing}');
})
I am looking to write the same thing every few seconds. Wrote the below code but it doesn't seem to work:
client.connect(PORT, function(){
setInterval(function(){
client.write('{ printing }');
},10000);
})
Following is the error that I keep getting:
node:events:355
throw er; // Unhandled 'error' event
^
Error: write EPIPE
at afterWriteDispatched (node:internal/stream_base_commons:160:15)
at writeGeneric (node:internal/stream_base_commons:151:3)
at Socket._writeGeneric (node:net:773:11)
at Socket._write (node:net:785:8)
at writeOrBuffer (node:internal/streams/writable:395:12)
at Socket.Writable.write (node:internal/streams/writable:340:10)
at Timeout._onTimeout (/app/src/index.js:135:14)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7)
Emitted 'error' event on Socket instance at:
at emitErrorNT (node:internal/streams/destroy:188:8)
at emitErrorCloseNT (node:internal/streams/destroy:153:3)
at processTicksAndRejections (node:internal/process/task_queues:81:21) {
errno: -32,
code: 'EPIPE',
syscall: 'write'
}
[nodemon] app crashed - waiting for file changes before starting..
This is how I fixed it:
client.connect(PORT, function(){
client.write('printing')
})
//adding drain if the buffer gets full
client.on('drain',()=>{
console.log("draining the buffer")
setTimeout(() => {
client.write('printing')
})
//reading the response recieved : ("ok")
client.on('data', (data) => {})
//in case of an error, closing the connection
client.on('error',err => {}).on('close',() => {
setTimeout(() => {
client.connect(PORT, function(){
client.write('printing')
})
},40000)
})
In this context, the EPIPE error probably means that you're trying to write to a socket that has been closed. Since the setInterval() example you show keeps going forever, that probably means that the socket you originally connected gets closed at some point, but your setInterval() is still firing and trying to write to it.
You don't show the overall context of what you're trying to accomplish here to know exactly what to suggest, but at a minimum, you need to call clearInterval() to stop the timer whenever the socket it's trying to write to gets closed, either on purpose or because of error.
Here's an example for how you could debug if this is what is happening to you:
const net = require('net');
const PORT = 3000;
const client = new net.Socket();
let timer;
function disableTimer() {
if (timer) {
clearInterval(timer);
timer = null;
}
}
client.on('error', err => {
console.log("socket error", err);
disableTimer();
}).on('close', () => {
console.log("socket closed");
disableTimer();
});
client.connect(PORT, function(){
timer = setInterval(function(){
client.write('{ printing }');
},10000);
});

I can not handle error event in net.createServer

proxy multiple proxies by net.createServer
here is my all code
var proxies='127.0.0.1:4444,127.0.0.1:4443,127.0.0.1:4442'.split(',');
var net = require('net');
function randgetir(){
d=proxies[Math.floor(Math.random() * proxies.length)].split(':');
return [d[0],d[1]];
}
var cre=net.createServer(function(from) {
var prgs=randgetir();
var to = net.createConnection({host: prgs[0],
port: prgs[1]
}).on('error', function(error) {
});
from.pipe(to);
to.pipe(from);
}).on('error', function(error) {
});
cre.listen("56666");
when i run the code sometimes i get
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:162:27)
Emitted 'error' event at:
at errorOrDestroy (internal/streams/destroy.js:98:12)
at Socket.onerror (_stream_readable.js:720:7)
at Socket.emit (events.js:197:13)
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
at processTicksAndRejections (internal/process/next_tick.js:76:17)
error and my app just crash and exit but as you see i handle all the error events,
what may i be doing wrong?
The problem is that there is no error handler attached to the incoming message stream. You could attach a handler like this:
from.on('error', function(e){ ...}))
.pipe(to);
Maybe check out this post on stackoverflow for more information regarding error handling with streams/pipes: Error handling with node.js streams

node-watch ECONNRESET on network drive

I have a small app that uses node-watch to watch 2 network drives and moves files between them when a change occurs. But the network often goes down, how do I prevent ECONNRESET crashes?
The code:
watch(directories.SQL_XML_IN, {
recursive: false,
filter: function (name) {
return /\.xml$/i.test(name);
}
}, function (evt, name) {
if (evt == 'update') {
// move files
}
});
And the error:
events.js:141
throw er; // Unhandled 'error' event
^
Error: watch null ECONNRESET
at exports._errnoException (util.js:870:11)
at FSEvent.FSWatcher._handle.onchange (fs.js:1217:21)
Try something like this:
var watcher = watch('...');
watcher.on('error', function(err) {
// handle errors
// close it if necessary
watcher.close()
});

ECONNREFUSED in Node http module

When a remote site is off-line I am getting this error in my consuming client (Node.js v0.12.0 with the http module):
Uncaught exception: connect ECONNREFUSED
Error: connect ECONNREFUSED
at exports._errnoException (util.js:746:11)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:983:19)
The code I'm currently using looks like this:
var req = http.request(options, function (res) {
res.on('socket', function (socket) {
socket.setKeepAlive(true, 0);
socket.setNoDelay(true);
});
res.on('end', function () {
log.debug('Success');
}).on('error', function () {
log.error('Response parsing failed');
});
}).on('error', function () {
log.error('HTTP request failed');
});
req.write(packet);
req.end();
The "error" event is never fired when the ECONNREFUSED occurs, I've tried using the "clientError" event but this is not fired either.
How can I capture this error?
Extracted from: https://stackoverflow.com/a/4328705/4478897
NOTE: This post is a bit old
The next example is with the http.createClient but i think it could be the same
Unfortunately, at the moment there's no way to catch these exceptions directly, since all the stuff happens asynchronously in the background.
All you can do is to catch the uncaughtException's on your own:
process.on('uncaughtException', function (err) {
console.log(err);
});
Maybe that helps you!
More this: https://stackoverflow.com/a/19793797/4478897
UPDATE:
did you tried to change log.error() to console.error() ???

Reconnect to TCP/IP socket on NodeJS

I use "net" library to create TCP connection on my nodeJs.
root.socket = net.createConnection(root.config.port, root.config.server);
I'm trying to handle error when remote server is down and reconnect in Cycle.
root.socket.on('error', function(error) {
console.log('socket error ' + error);
root.reconnectId = setInterval(function () {
root.socket.destroy();
try {
console.log('trying to reconnect');
root.socket = net.createConnection(root.config.port, root.config.server);
} catch (err) {
console.log('ERROR trying to reconnect', err);
}
}, 200);
}
The trouble is that in case of remote server shutdown I still get en error and my nodeJS server stops.
events.js:72
throw er; // Unhandled 'error' event
^ Error: connect ECONNREFUSED
at errnoException (net.js:904:11)
at Object.afterConnect [as oncomplete] (net.js:895:19)
You will need something like this:
var net = require('net');
var c = createConnection(/* port, server */);
function createConnection(port, server) {
c = net.createConnection(port, server);
console.log('new connection');
c.on('error', function (error) {
console.log('error, trying again');
c = createConnection(port, server);
});
return c;
}
In your case you are creating a new connection but you don't attach any error listener, the error is raised somewhere else in the execution loop and can not be caught by the "try / catch" statement.
P.S. try to avoid using "try / catch" statement, error handling in Node.JS is made using error listeners and domains, it can be useful only for JSON.parse() or other functions that are executed synchronously.

Resources