简体   繁体   中英

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.

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.
    });
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM