Node.js Error: connect ECONNREFUSED thrown by client - node.js

I have set up a node program (actually two, one for the server and one for the client) but I get this error from my client every time I run it:
events.js:85
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED
The code for the server:
var net = require('net');
var server = net.createServer(function (socket) {
console.log('Connection from ' + socket.remoteAddress);
socket.end('hello world')
});
server.listen(7000, '0.0.0.0')
This works fine. As for my client code, not so much. Here is my client code:
var net = require('net');
var client = new net.Socket();
client.connect(7000, 'IP of server here'); // in my actual code, I used the actual ip, of course
client.on('data', function(data) {
console.log('Data: ' + data);
client.destroy();
});
client.on('close', function () {
console.log('Connection closed');
});
This is one of my first node programs, and it is my first using TCP, so expect a newbie mistake. Thanks in advance for the help.

You need to handle the "error" event to avoid the default exception throw:
client.on('error', (error) => {
// treat error here
})

Related

NodeJS TCP Port crashes

I am developing socket application in my server with node js. I am just listening 9000 port. I am checking the data that client sent to this tcp port, if a client made http request, I kick client from server. Because some bots in the internet does that and I dont want them in my system. Due to test purposes, I try to connect that port with a browser, hold down F5 refresh button continuously, then application crashes immediately. I am simulating the DDOS attacks in my port by this way. The error message as follows:
events.js:183
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at _errnoException (util.js:992:11)
at TCP.onread (net.js:618:25)
And here is my basic TCP listener code
var net = require("net");
var server = net.createServer();
server.on("error", err =>
{
console.log("error handled, error is : %s",err);
});
server.on("connection",function(socket)
{
var remoteAddress = socket.remoteAddress;
console.log("new client connection %s",remoteAddress);
socket.end();
});
server.listen(9000, function()
{
console.log("I am listening.");
});
What can be done to save TCP port from HTTP connections and internet bots?
Put this under socket.end():
socket.on('error', function(error) {
console.log('Socket got problems: ', error.message);
});
full code:
var net = require("net");
var server = net.createServer();
server.on("error", err =>
{
console.log("error handled, error is : %s",err);
});
server.on("connection",function(socket)
{
var remoteAddress = socket.remoteAddress;
console.log("new client connection %s",remoteAddress);
socket.end();
socket.on('error', function(error) {
console.log('Socket got problems: ', error.message);
});
});
server.listen(9000, function()
{
console.log("I am listening.");
});

Node JS detect if named pipe exists

I'm trying to use named pipes in my application. The problem is when I try to connect to the named pipe before the server is running, I get the following error:
events.js:141
throw er; // Unhandled 'error' event
^
Error: connect ENOENT \\?\pipe\\testpipe
at Object.exports._errnoException (util.js:870:11)
at exports._exceptionWithHostPort (util.js:893:20)
at PipeConnectWrap.afterConnect [as oncomplete] (net.js:1062:14)
How can I check if the pipe exists before attempting to connect to it?
Note: Wrapping my connect code in a try-catch doesn't prevent the error.
Here is my code:
var net = require('net');
var addr = '\\\\?\\pipe\\testpipe';
var client = net.createConnection({ path: addr }, function() {
console.log("Connected");
client.on('data', function(data) {
console.log("Recieved: " + data);
});
client.on('error', function(){
console.log(arguments);
});
}.bind(this));
Using the domain module prevents a fatal error. The following code can be used to safely run the connect code.
Not what I was hoping for, but the closed solution since there have been no answers.
var net = require('net');
var domain = require('domain');
var addr = '\\\\?\\pipe\\testpipe';
var d = domain.create();
d.on('error', function(err) {
console.error(err);
});
d.run(function() {
var client = net.createConnection({ path: addr }, function() {
console.log("Connected");
client.on('data', function(data) {
console.log("Recieved: " + data);
});
client.on('error', function(){
console.log(arguments);
});
}.bind(this));
});
make the socket, then listen for an error event, then call connect and it won't be thrown: https://nodejs.org/api/net.html#net_event_error_1

node.js server socket.io-client with SSL

I try to setup two node.js servers communication with each other over socket.io. The node servers use SSL, but I don't get it running. I do not get any feedback, its close to this:
Node.js socket.io-client connect_failed / connect_error event
This will not work. No response.
var clientio = require('socket.io-client');
console.log('Trying stuff ...');
// the channel does not exist
var socket = clientio.connect( 'http://localhost:4000/news' );
// I expect this event to be triggered
socket.on('connect_failed', function(){
console.log('Connection Failed');
});
socket.on('connect', function(){
console.log('Connected');
});
socket.on('disconnect', function () {
console.log('Disconnected');
});
but if I try:
// Bind to the news namespace, also get the underlying socket
var ns_news = clientio.connect( 'https://localhost:9000' );
var socket = ns_news.socket
// Global events are bound against socket
socket.on('connect_failed', function(){
console.log('Connection Failed');
});
socket.on('connect', function(){
console.log('Connected');
});
socket.on('disconnect', function () {
console.log('Disconnected');
});
// Your events are bound against your namespace(s)
ns_news.on('myevent', function() {
// Custom event code here
});
I can see that ns_news has no element socket, so I get:
TypeError: Cannot call method 'on' of undefined
So how do I connect these two servers with feedback if the connection is successful or not?
And my following question would be:
How can these two servers authenticate to each other?
Means: Server A says to server B:
- hey, gimme that secret string
And Server B checks the certificate of server A and if it's ok
- here's the string
How do I do it with node?

net Node.js Error: read ECONNRESET (on Windows)

I am attempting to use the net lib in Node.js to do simple message passing. In the example on Nodejs.org they provide the following code as a basic echo server:
var net = require('net');
var server = net.createServer(function(c) { //'connection' listener
console.log('server connected');
c.on('end', function() {
console.log('server disconnected');
});
c.write('hello\r\n');
c.pipe(c);
});
server.listen(8124, function() { //'listening' listener
console.log('server bound');
});
and a client for said server:
var net = require('net');
var client = net.connect({port: 8124},
function() { //'connect' listener
console.log('client connected');
client.write('world!\r\n');
});
client.on('data', function(data) {
console.log(data.toString());
client.end();
});
client.on('end', function() {
console.log('client disconnected');
});
The example above works, however, if you remove the client.end(); from the client code and force close the script on the client end (simulating a client crashing) the server crashes as well with the error:
Error: read ECONNRESET
at errnoException (net.js:904:11)
at TCP.onread (net.js:558:19)
I attempted to catch the error in the server code with c.on("error",function(){}) as well as server.on('error', function (e) {}); but in both cases the server still crashes when the client disconnects without using client.end()
What is the propper way of checking for this error so that the server does a console.log('connection reset by peer') instead of crashing?
UPDATE:
I tried this same code on my linux box and it seems to work just fine ... so why does it work in linux but not in windows?
you can catch that error by adding this code inside yours 'createServer' function:
process.on('uncaughtException', function (err) {
console.error(err.stack);
console.log("Node NOT Exiting...");
});

Node JS Server to Server Connection

Is it possible to connect to a NodeJS Server from another server? Two NodeJS servers communicating with each other?
//Server Code
var io = require('socket.io').listen(8090);
io.sockets.on('connection', function (socket) {
io.sockets.emit('this', { will: 'be received by everyone'});
socket.on('private message', function (from, msg) {
console.log('I received a private message by ', from, ' saying ', msg);
});
socket.on('disconnect', function () {
io.sockets.emit('user disconnected');
});
});
//Client Code in Server Code. Connecting to another server.
io.connect( "http://192.168.0.104:8091" ); //Connect to another server from this one.
//ETC...
Here's a simple example that creates a server and a client that connects to that server. Remember that what you send has to be a buffer (strings are automatically converted to buffers). The client and server works independently of eachother, so can be put in the same app or on totally different computers.
Server (server.js):
const net = require("net");
// Create a simple server
var server = net.createServer(function (conn) {
console.log("Server: Client connected");
// If connection is closed
conn.on("end", function() {
console.log('Server: Client disconnected');
// Close the server
server.close();
// End the process
process.exit(0);
});
// Handle data from client
conn.on("data", function(data) {
data = JSON.parse(data);
console.log("Response from client: %s", data.response);
});
// Let's response with a hello message
conn.write(
JSON.stringify(
{ response: "Hey there client!" }
)
);
});
// Listen for connections
server.listen(61337, "localhost", function () {
console.log("Server: Listening");
});
Client (client.js):
const net = require("net");
// Create a socket (client) that connects to the server
var socket = new net.Socket();
socket.connect(61337, "localhost", function () {
console.log("Client: Connected to server");
});
// Let's handle the data we get from the server
socket.on("data", function (data) {
data = JSON.parse(data);
console.log("Response from server: %s", data.response);
// Respond back
socket.write(JSON.stringify({ response: "Hey there server!" }));
// Close the connection
socket.end();
});
The conn and socket objects both implement the Stream interface.
Check Substrack's dnode. It auto maps literal objects from the 1st env to the 2nd one. You gain a kind of RPC out of the box. And it works in the browser too...

Resources