0

Hello I am working on Node js sockets. I am listening data from multiple devices through ip and port. After running for a while I get this exception and my program stops

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: read ECONNRESET
    at errnoException (net.js:905:11)
    at TCP.onread (net.js:559:19)

This is the code I have written

var net = require('net');
var request = require('request');



var net = require('net');
var HOST = '172.xx.x.xx';
var PORT = 52xx;
var cluster = require('cluster');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
    // Fork workers.
    for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
    }

    cluster.on('death', function(worker) {
        console.log('worker ' + worker.pid + ' died');
        cluster.fork();
    });
} else {
    net.createServer(function(socket){
         console.log('received connection...');
        socket.on('data', function(data) {

            var options = {
  uri: 'http://demourl/api',
  method: 'POST',
  body: {
    message:data.toString()
  },
  json: true 

};
             console.log(data.toString());

             request(options, function (error, response, body) {

});

        });


    }).listen(PORT, HOST);
}

How can I catch an error and prevent my program from stopping.

user1hjgjhgjhggjhg
  • 1,237
  • 4
  • 15
  • 34
  • use `socket.on("error", (err) => console.log("socket error: ") console.log(err.stack); socket.destroy(); )` and – itaintme Jul 16 '18 at 19:10
  • @itaintme could you please tell me where should I insert this code in my code. I am getting an error. I think I may be putting at the wrong place? – user1hjgjhgjhggjhg Jul 16 '18 at 19:27

1 Answers1

0

include socket.on("error", ... like this. Have a look at this question

socket.on("error", (err) =>
    console.log("socket error: ")
    console.log(err.stack);
    socket.destroy();
)
itaintme
  • 1,575
  • 8
  • 22
  • could you please tell me where should I insert this code in my code. I am getting an error. I think I may be putting at the wrong place? – user1hjgjhgjhggjhg Jul 16 '18 at 19:27
  • @user1hjgjhgjhggjhg inside `net.createServer(...` Did you check out the other so link I posted in my answer? – itaintme Jul 16 '18 at 19:49