Mustafa
Mustafa

Reputation: 1776

Why am i getting this error running 'net' module node.js

I am using .net modular and opening tcp port on 6112.

var net = require('net');
    var server = net.createServer(function (socket) { //'connection' listener
    });
server.listen(6112, function () { //'listening' listener
    console.log('server started');
});

On the same machine i start a java socket in main.

public static void main(String[] args) {
        // TODO Auto-generated method stub

        try {
            System.out.println("Connecting...");
            Socket socket = new Socket("localhost", 6112);
            System.out.println("Connected");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

I get this exception,

C:\Users\Mustafa\WebstormProjects\Node.Js>node hello.js
server started

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

Is this like a bug or something, cause if once i get through this bug, I will be good thanks.

I haven't used the debugger cause as Ryan said it him self a year ago that it is still shitt.

Upvotes: 3

Views: 5024

Answers (2)

loganfsmyth
loganfsmyth

Reputation: 161477

You need to listen for errors on the socket. Node has the default behavior that when something does .emit('error'), if there are no error handlers attached, it will throw the error instead, thus crashing the application.

var server = net.createServer(function (socket) {
    socket.on('error', function(err){
        // Handle the connection error.
    });
});

Upvotes: 8

user568109
user568109

Reputation: 48003

You are creating a socket and connecting from it, but not closing it. So when the program finishes, to node.js it looks like connection is reset (closed abruptly). Call socket.close(); before program finishes.

You can structure your code in this way :

try {
    tryStatements      //your code that is causing exceptions
}
catch(exception){
    catchStatements    //handle caught exceptions
}
finally {
    finallyStatements  //execute it anyways
}

Or if you like to catch uncaught exceptions from runtime, use this (main process won't exit on exceptions)

process.on('uncaughtException', function(err) {
    console.log('Caught exception: ' + err);
    console.log(err.stack);
});

The problem is in java code which is causing node.js to exit on exception. So be sure to add socket.close();. Above is just error handling on node.js part.

Upvotes: 0

Related Questions