node 'net' module ECONNREFUSED error - javascript

I'm looking at this page: http://nodejs.org/api/net.html#net_net_createconnection_options_connectionlistener
Running the code from the page:
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');
});
and I'm getting the error:
events.js:72
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED
at errnoException (net.js:901:11)
at Object.afterConnect [as oncomplete] (net.js:892:19)
shell returned 8
version stuff:
~ % node --version
v0.10.25
~ % uname -a
Linux human1 3.13.0-031300-generic #201401192235 SMP Mon Jan 20 03:36:48 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
I've tried a lot of different ports and I'm positive node isn't already running

Is the net server you're trying to connect to running?
I tried this and it works for me:
net.js
var net = require('net');
var server = net.createServer(function(client) {
console.log('connected');
});
server.listen(8124);
var client = net.connect({port: 8124}, function() {
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');
});
Run:
$ node net.js
connected
client connected

Related

I have an error with my TCP nodejs server

I wanna make an tcp server with nodejs . When i start the server in the terminal it says nothing, and when i start the client the client gets the message but in the server terminal, it prints:
events.js:292
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:209:20)
Emitted 'error' event on Socket instance at:
at Socket.onerror (internal/streams/readable.js:760:14)
at Socket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
errno: -54,
code: 'ECONNRESET',
syscall: 'read'
}
When i start the client again, the server is still running, i needed to stop the server using killall node.
How can i fix this error.
Server:
var net = require('net');
var server = net.createServer(function(socket) {
socket.write('Connected to server !\r\n');
socket.pipe(socket);
});
server.listen(1337, '127.0.0.1');
Client:
var net = require('net');
var client = new net.Socket();
client.connect(1337, '127.0.0.1', function() {
console.log('Connected');
client.write('Hello, server! Love, Client.');
});
client.on('data', function(data) {
console.log('Received: ' + data);
client.destroy(); // kill client after server's response
});
client.on('close', function() {
console.log('Connection closed');
});

Connect to a device over UDP with nodejs

I have a TCP/IP device that I have written script in python to connect and receive data from and this works. I am now trying to do something similar with nodejs but keep running in to either connection errors or security issues with the buffer depending on the nodejs methods I have tried.
This is the python script that works;
import socket
import csv
import datetime
from decimal import Decimal
import time
UDP_IP = "10.0.0.122"
UDP_PORT = 1025
MESSAGE = "#01\r"
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE.encode(encoding='utf-8'), (UDP_IP, UDP_PORT))
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print ("received message:", str(data))
Here are 3 methods I have tried with varying errors listed in comments in js. I am new to node js and could really do with some help.
Thanks in advance
// //Method 1
// var net = require('net');
// var client = new net.Socket();
// client.connect(1025, '10.0.0.122', function() {
// console.log('Connected');
// client.write('Hello, server! Love, Client.');
// });
// client.on('data', function(data) {
// console.log('Received: ' + data);
// client.destroy(); // kill client after server's response
// });
// client.on('close', function() {
// console.log('Connection closed');
// });
//Method 2
// // Include Nodejs' net module.
// const Net = require('net');
// // The port number and hostname of the server.
// const port = 1025;
// const host = '10.0.0.122';
// // Create a new TCP client.
// const client = new Net.Socket();
// // Send a connection request to the server.
// client.connect({ port: port, host: host }), function() {
// // If there is no error, the server has accepted the request and created a new
// // socket dedicated to us.
// console.log('TCP connection established with the server.');
// // The client can now send data to the server by writing to its socket.
// client.write('#01\r');
// };
// // The client can also receive data from the server by reading from its socket.
// client.on('data', function(chunk) {
// console.log(`Data received from the server: ${chunk.toString()}.`);
// // Request an end to the connection after the data has been received.
// client.end();
// });
// client.on('end', function() {
// console.log('Requested an end to the TCP connection');
// });
//Method 1 and 2 give this error
// events.js:287
// throw er; // Unhandled 'error' event
// ^
// Error: connect ECONNREFUSED 10.0.0.122:1025
/ / at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)
// Emitted 'error' event on Socket instance at:
// at emitErrorNT (internal/streams/destroy.js:92:8)
// at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
// at processTicksAndRejections (internal/process/task_queues.js:84:21) {
// errno: 'ECONNREFUSED',
// code: 'ECONNREFUSED',
// syscall: 'connect',
// address: '10.0.0.122',
// port: 1025
// }
//Method 3
var PORT = 1025;
var HOST = '10.0.0.122';
var dgram = require('dgram');
var message = new Buffer('#01\r');
var client = dgram.createSocket('udp4');
client.send(message, 0, message.length, PORT, HOST, function(err, bytes) {
if (err) throw err;
console.log('UDP message sent to ' + HOST +':'+ PORT);
client.close();
});
//Method 3 error
// [Running] node "c:\Users\admin\Nodejs tcp test\app.js"
// (node:6032) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability
issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
// UDP message sent to 10.0.0.122:1025
// [Done] exited with code=0 in 0.155 seconds
I have figured it with a little help from google. There are some good examples for a UDP connection in js.
With a pointer in the right direction from Rodrigoms github project,
https://github.com/rodrigoms2004/ServerSocketTCP_UDP
I managed to achieve the same as I was getting in my python file using the following code.
const udp = require('dgram')
// creating a client socket
const client = udp.createSocket('udp4')
//buffer msg
const data = Buffer.from('#01\r')
client.on('message', (msg, info) => {
console.log('Data received from server : ' + msg.toString())
console.log('Received %d bytes from %s:%d\n', msg.length, info.address, info.port)
})
//sending msg
client.send(data, 1025, '10.0.0.122', error => {
if (error) {
console.log(error)
client.close()
} else {
console.log('Data sent !!!')
}
})
setTimeout( () => {
client.close()
},1000)

{ [Error: listen EADDRINUSE :::5000]

What's wrong with the following Server.JS file? We are trying to connect Deployd to Heroku and keep getting the following error. We're using Nitrous, and I have configure the mongoDB port to 5000. Any help is appreciated. Thanks a ton!
Server.JS
// require deployd
var deployd = require('deployd');
// configure database etc.
var server = deployd({
port: process.env.PORT || 5000,
env: 'production',
db: {
host: '0.0.0.0',
port: 5000,
name: 'database_name',
credentials: {
username: 'username',
password: 'password'
}
}
});
// heroku requires these settings for sockets to work
server.sockets.server.set('transports', ["xhr-polling"]);
// start the server
server.listen();
// debug
server.on('listening', function() {
console.log("Server is listening on port: " + process.env.PORT);
});
// Deployd requires this
server.on('error', function(err) {
console.error(err);
process.nextTick(function() { // Give the server a chance to return an error
process.exit();
});
});
ERROR:
db:error Error: Cannot open store: MongoError: server 0.0.0.0:5000 timed out
at /home/nitrous/Find-Volunteerships/node_modules/deployd/lib/db.js:144:17
at /home/nitrous/Find-Volunteerships/node_modules/mongodb/lib/mongo_client.js:330:20
at /home/nitrous/Find-Volunteerships/node_modules/mongodb/lib/db.js:231:14
at null.<anonymous> (/home/nitrous/Find-Volunteerships/node_modules/mongodb/lib/server.js:240:9)
at g (events.js:260:16)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at /home/nitrous/Find-Volunteerships/node_modules/mongodb-core/lib/topologies/server.js:493:23
at commandCallback (/home/nitrous/Find-Volunteerships/node_modules/mongodb-core/lib/topologies/server.js:1149:20)
at Callbacks.flushConnection (/home/nitrous/Find-Volunteerships/node_modules/mongodb-core/lib/topologies/server.js:103:9)
at null.<anonymous> (/home/nitrous/Find-Volunteerships/node_modules/mongodb-core/lib/topologies/server.js:408:24)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at null.<anonymous> (/home/nitrous/Find- Volunteerships/node_modules/mongodb-core/lib/connection/pool.js:144:10)
at g (events.js:260:16)
at emitTwo (events.js:87:13) +0ms
session:error Error removing old sessions: Database connection error +14ms
Unhandled rejection Database connection error
{ [Error: listen EADDRINUSE :::5000]
code: 'EADDRINUSE',
errno: 'EADDRINUSE',
syscall: 'listen',
address: '::',
port: 5000 }
You are using same port for two servers.
You can kill one of them with that command
netstat -ano|findstr "PID :5000"
5000 is your port.

nodejs tcp client-server error

I am trying to get nodejs client-server with tcp working. This is my code:
server.js containing the code for server
var net = require('net');
var server = net.createServer(function(socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
});
console.log("Started Server");
server.listen(1337, '127.0.0.1');
client.js containing the code for client
var net = require('net');
var client = new net.Socket();
client.connect(1337, '127.0.0.1', function() {
console.log('Connected');
client.write('Hello, server! Love, Client.');
});
client.on('data', function(data) {
console.log('Received: ' + data);
client.destroy(); // kill client after server's response
});
client.on('close', function() {
console.log('Connection closed');
});
when I run in 2 separate terminals node server.js , node client.js I get this error:
Started Server
events.js:154
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at exports._errnoException (util.js:856:11)
at TCP.onread (net.js:546:26)
Process finished with exit code 1
But if i Combine both of the codes together in a single process it works fine. Anyone have any idea what the problem can be?

ECONNREFUSED when starting node express application

events.js:141
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED 127.0.0.1:4562
at Object.exports._errnoException (util.js:837:11)
at exports._exceptionWithHostPort (util.js:860:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1060:14)
here is my code
var express = require('express');
var net = require('net');
var app = express();
var i = 0;
app.get('/', function (req, res)
{
i = i+1; //no of clinets request gin ne ki liye
console.log(i + "fa..sa");
var client = net.connect({port: 4562},"192.168.202.101", function() {
console.log('connected to server!'); });
client.write("Ho gaya bhai");
client.end();
res.send('ho gaya bhai..');
});
app.listen(6544);
As you can see from your error message you have an error in the way you call net.connect. It looks like you want to connect to 192.168.202.101:4562, but you try to connect to ´127.0.0.1:4562´. Try either:
net.connect({ port: 4562, host: "192.168.202.101"}, function(){});
or:
net.connect(4562, "192.168.202.101", function() {});

Categories

Resources