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

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.

Related

Handling an error on a tcp connection using the "net" module of NodeJS

Im trying to learn the "net" module of NodeJS, but i have run into an annoying problem. My code is in 2 scripts.
//index.js
var net = require("net")
var server = net.createServer(socket=>{
socket.write("Hello!")
})
server.on("error", err=>{
console.error(err)
})
server.listen(50001)
and
//client
var net = require("net")
net.createConnection({
host:"localhost",
port: 50001
})
.on("data", data=>{
console.log(data.toString())
})
when i run the 2 scripts...
node index.js
node client.js
...the message "Hello!" is sent to the client with no problems. If i CTRL+C out of the client (to simulate an unexpected closure), i get the following error
events.js:174
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:111:27)
Emitted 'error' event at:
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
which i find strange, as I have registered an "error" event on the server. What am i doing wrong?
The program registers a handler for an 'error' event on the server's listening socket, but it does not register an 'error' handler on the separate new socket that is created to carry the connection that is made by the client. (Every connection to the server gets a separate new socket, distinct from the listening socket and from any other connections that have been made earlier.)
That new connection socket is the one that is passed as the argument to the server's connect handler. It's the socket that you write 'Hello!' into.
If you want the program to be notified of an error on that new socket then you must register an 'error' handler on the new socket. Something like this:
var net = require("net")
var server = net.createServer(socket=>{
socket.on('error', err=>{
console.error('connected socket: ' + err);
});
socket.write("Hello!")
})
server.on("error", err=>{
console.error(err)
})
server.listen(50001)
Similarly, if you wanted the server to read data from the connection then you would register a handler for the 'data' event on the new connection socket, in the same way as you already did on the client's socket.

Node.js and Zaproxy UnhandledPromiseRejectionWarning: RequestError: Error: socket hang up

var zapClient = require('zaproxy');
const zapOptions = {
key : 'abcdefghijklmn',
proxy : 'http://localhost:8090/'
};
const zaproxy = new zapClient(zapOptions);
zaproxy.spider.scan("https://www.google.co.in");
i am trying to run above code i am getting :
(node:8380) UnhandledPromiseRejectionWarning: RequestError: Error: socket hang up error.
i have tried socket hang up error with nodejs and "Request error: Socket hang up" with nodeJS on Amazon EC2 didn't help.
I believe changing the last line of your code to this should fix the problem:
zaproxy.spider.scan("https://www.google.co.in", (err, res) => {
if (err) throw err;
//do something with res here
});
//can't do anything with res here
Also check the zap.log file - that might be logging errors which by default are not reported to the client (for security reasons - this can be disabled for testing)

How to prevent "Error: connect ECONNREFUSED"

I'm currenlty working on a TS3 query bot written in node.js.
I added an auto reconnect to it but I have the issue now that the bot crashes if the server is offline with the following error:
events.js:85
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED
at exports._errnoException (util.js:746:11)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:983:19)
The line which starts the connection is the following:
var cl = new ts3.TeamSpeakClient(config.serverIP);
used with the node-ts api -> https://github.com/nikeee/node-ts
I already added the following events:
cl.on('error', function(err){
console.log("bla: " + err)
});
cl.on('uncaughtException', function (err) {
console.log(err);
});
uncaughtException doesn't get triggered and error doesn't prevent the crash.
How can I prevent it from crashing?
Edit: It's async btw.
You need to catch the UncaughtException on the process rather than in ts3 object.
process.on('uncaughtException', function (err) {
console.log(err);
})
More on handling exceptions can be found over here.
UPDATE:
cl has its own fail promise as well. To be implemented like this:
cl.fail(function(err) {
console.log("An error occurred." + util.inspect(err))
});

Node.js http.createServer how to get error

I am new to node.js and am trying to experiment with basic stuff.
My code is this
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
Here's the question - how can I see the exceptions thrown (or events thrown) when calling createServer ? I tried try/catch but it doesn't seem to work . In module's API I couldn't find any reference to it . I am asking because I accidentally started a server on a taken port(8888) and the error I got (in command-line) was Error : EDDRINUSE , this is useful enough but it would be nice to be able to understand how errors are caught in node .
You can do this by handling the error event on the server you are creating. First, get the result of .createServer().
var server = http.createServer(function(request, response) {
Then, you can easily handle errors:
server.on('error', function (e) {
// Handle your error here
console.log(e);
});
Print stacktrace of uncaught exceptions using following code.
process.on('uncaughtException', function( err ) {
console.error(err.stack);
});
The error is emitted in the listen() method. The API documentation includes an example just for your situtation.
You can use
process.on('uncaughtException', function(e){
console.log(e);
});
To handle uncaught exceptions. Any unhandled exception from the web server could be caught like this.

Catch exception in node.js

I have a simple program, which needs to make sure I can connect to a Redis server. I use node-redis to connect and need to wait until Redis is started. I use this piece of code:
function initializeRedis(callback) {
(function createClient(){
var runner;
try {
client = redis.createClient();
} catch (e) {
setTimeout(createClient, 1000);
}
callback();
})();
};
initializeRedis(function() {
// Work here
});
This is because without the try/catch, I got an exception from node.js:
node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^ Error: Redis connection to 127.0.0.1:6379 failed - ECONNREFUSED, Connection refused
at Socket.<anonymous> (/var/www/php-jobs/node_modules/redis/index.js:88:28)
at Socket.emit (events.js:64:17)
at Array.<anonymous> (net.js:830:27)
at EventEmitter._tickCallback (node.js:126:26)
When I start redis-server (Ubuntu machine) and start this script, everything works fine. If I stop redis-server and start the script, it doesn't catch the exception and still throws this same exception. How is that possible? I have a try/catch statement!
After client = redis.createClient();, set a handler for the error event:
client.on('error', function(err) {
// handle async errors here
});
Have a look at the stack trace - your code isn't in it, so there's no place where a try/catch could catch the error.

Categories

Resources