Getting 'ECONNREFUSED' error when socket connection is established on different host - node.js

Apparently, I am testing out simple TCP server that uses Node.js.
The server code, and the client code works well if they are both on the same machine.
However, it seems that when I run the server on the different machine and test to connect to the server from the client in different machine, I get error like below.
Error: connect ECONNREFUSED
at errnoException (net.js:589:11)
at Object.afterConnect [as oncomplete] (net.js:580:18)
I tried by typing IP address of the server, or the domain name of the server, but no luck.
The server code is like below, (server was ran with root privilege..)
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 6969;
net.createServer(function(sock) {
console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
sock.on('data', function(data) {
console.log('DATA ' + sock.remoteAddress + ': ' + data);
sock.write('You said "' + data + '"');
});
sock.on('close', function(data) {
console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
});
}).listen(PORT, HOST);
console.log('Server listening on ' + HOST +':'+ PORT);
and the client code is like below
var net = require('net');
var HOST = '127.0.0.1'; //I set it to server IP address but no luck..
var PORT = 6969;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('I am Chuck Norris!');
});
client.on('data', function(data) {
console.log('DATA: ' + data);
client.destroy();
});
client.on('close', function() {
console.log('Connection closed');
});
Is there any configuration that I have to go through, if I want the server to accept socket connections from different machine? Do I have to run server code as production mode (if there is such mode)?? Or, is there limitation in port range?

Set the server to bind to 0.0.0.0 and set the client to connect to the correct IP address of the server. If the server is listening on 127.0.0.1, it will only accept connections from its local host.

Related

nodejs UDP server isn't receiving messages from luasocket

I can't seem to get the following communication working. Is it something to do with repl.it or am I just missing something?
client code - lua
local host, port = "test.abstractpoo.repl.co", 7865
local socket = require("socket")
local ip = assert(socket.dns.toip(host))
local udp = assert(socket.udp4())
assert(udp:setpeername(ip, port))
assert(udp:send("anything"))
server code - nodejs
var PORT = 7865;
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
server.on("connect", function() {
console.log("client connected")
})
server.on('listening', function() {
var address = server.address();
console.log('UDP Server listening on ' + address.address + ':' + address.port);
});
server.on('message', function(message, remote) {
console.log(remote.address + ':' + remote.port + ' - ' + message);
});
server.bind(PORT);

How to make different users connect to the same socket?

I'm writing a simple chat app using Node.js. The server-side code is :
const net = require('net');
const HOST = 'localhost';
const PORT = 3000;
const server = net.createServer();
server.listen(PORT, HOST);
server.on('connection', (socket) => {
console.log(socket.localPort);
console.log(socket.remotePort);
console.log('CONNECTED: ' + socket.remoteAddress +':'+ socket.remotePort);
socket.on('data', (data) => {
console.log('DATA ' + socket.remoteAddress + ': ' + data);
// Write the data back to the socket, the client will receive it as data from the server
socket.write('You said "' + data + '"');
});
socket.on('close', () => {
console.log('CLOSED: ' + socket.remoteAddress +' '+ socket.remotePort);
});
socket.on('error', () => {
console.log('ERROR OCCURED:');
});
});
console.log('Server listening on ' + HOST +':'+ PORT);
The problem is that, when a client connects to the server, the socket object is UNIQUE every time a client connects, so the different clients cannot exchange messages.
How I can make different users connect to same socket so they can exchange messages?

Trying to write an Integer value through node js socket, but can't do that

Am trying to post some string from my tcp client to tcp server(Both were implemented using NodeJS). Once I receive message from client I need to write some integer value in the same socket. But when I tried writing the integer value, am getting an exception saying "Invalid Data". Can you please help me to understand or fix this.
Server Code:
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 6969;
net.createServer(function(sock) {
console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
sock.on('data', function(data) {
console.log('DATA ' + sock.remoteAddress + ': ' + data);
sock.write(data.length);
});
sock.on('close', function(data) {
console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
});
}).listen(PORT, HOST);
console.log('Server listening on ' + HOST +':'+ PORT);
Client Code
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 6969;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('I am Chuck Norris!');
});
client.on('data', function(data) {
console.log('DATA: ' + data);
client.destroy();
});
client.on('close', function() {
console.log('Connection closed');
});
Output:
CONNECTED: 127.0.0.1:56183 DATA 127.0.0.1: I am Chuck Norris!
net.js:612
throw new TypeError('invalid data');
Try this:
var writeBuffer = Buffer(1);
writeBuffer[0] = 1; //Value to send
.
.
client.write(writeBuffer);
The output says it all, invalid data!
request.write(chunk[, encoding][, callback])
The chunk argument should be a Buffer or a string.
sock is Stream, you can write Buffer or string into stream.
You should read the documentation of nodejs here https://nodejs.org/api/http.html#http_request_write_chunk_encoding_callback
What are you trying to achieve, communication between processes?

How to test socket.setKeepAlive in NodeJS

I tried to test the function of setKeepAlive() in NodeJS. I ran Server.js and client.js on different machines within same local network. Then, I turned off the wifi connection on the client machine (break the internet connection). After 15 minutes, there is still no message thrown. Why is that? Didn't setKeepAlive() work?
Here is the code of the server and client:
Client.js
var net = require('net');
var HOST = '192.168.0.16';
var PORT = 8333;
var client = net.connect(PORT, HOST, function connected(){
console.log('connected');
});
client.setKeepAlive(true, 1);
client.write('hi server');
client.on('data', function(data) {
console.log('Received' + data);
});
client.on('close', function(){
console.error('connection closed');
)};
client.on('error', function(err){
console.error('error', err);
});
Server.js
var net = require('net');
var HOST = '192.168.0.16';
var PORT = 8333;
net.createServer(function(sock) {
console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);
sock.on('data', function(data) {
console.log('DATA ' + sock.remoteAddress + ': ' + data);
sock.write('hi client');
});
sock.on('close', function(data) {
console.log('CLOSED: ' +
sock.remoteAddress + ' ' + sock.remotePort);
});
sock.on('error', function(error){
console.log('error', error);
});
}).listen(PORT, HOST);
console.log('Server listening on ' + HOST +':'+ PORT);
I would implement keep_alive by myself using both setInterval(sendKeepAliceFunc, delay), and socket.setTimeout()
Delay between keep_alive message should be big enough (~10000ms), it not valid if delay < round trip (?)
I think the original keepalive feature is not reliable. I have success enable it on other programming language (C# and C) and I can trace network and see KEEP_ALIVE packets, but then it NOT work in some circumstances (special network configuration, people may run app in virtual machine, ...)
So I suggest implement it by yourself, you can implement a your own socket with the same APIs but also has your new keepalive feature.

Create WebSockets between a TCP server and HTTP server in node.js

I have created a TCP server using Node.js which listens to clients connections.
I need to transmit data from TCP server to HTTP server again in Node.js possibly through a Websocket (socket.io).
However, I do not know how to create such connection such that TCP server is able to push data to HTTP server through Websocket.
Many Thanks.
I was trying lot of things to get this work. Most of the time I was relying on socket.io to get this working, but it was just not working with TCP.
However, net.Socket suffices the purpose.
Here is the working example of it.
TCP Server
var net = require('net');
var HOST = 'localhost';
var PORT = 4040;
var server = net.createServer();
server.listen(PORT, HOST);
server.on('connection', function(sock) {
console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
sock.write("TCP sending message : 1");
console.log('Server listening on ' + server.address().address +':'+
server.address().port);
}).listen(PORT, HOST);
HTTP Server
var http = require('http').createServer(httpHandler),
fs = require("fs"),
wsock = require('socket.io').listen(http),
tcpsock = require('net');
var http_port = 8888;
var tcp_HOST = 'localhost';
var tcp_PORT = 4040;
/**
* http server
*/
function httpHandler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
http.listen(http_port);
console.info("HTTP server listening on " + http_port);
wsock.sockets.on('connection', function (socket) {
var tcpClient = new tcpsock.Socket();
tcpClient.setEncoding("ascii");
tcpClient.setKeepAlive(true);
tcpClient.connect(tcp_PORT, tcp_HOST, function() {
console.info('CONNECTED TO : ' + tcp_HOST + ':' + tcp_PORT);
tcpClient.on('data', function(data) {
console.log('DATA: ' + data);
socket.emit("httpServer", data);
});
tcpClient.on('end', function(data) {
console.log('END DATA : ' + data);
});
});
socket.on('tcp-manager', function(message) {
console.log('"tcp" : ' + message);
return;
});
socket.emit("httpServer", "Initial Data");
});
Browser Client
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('httpServer', function (data) {
console.log(data);
document.write(data + "\r\n");
socket.emit('tcp', "For TCP");
});
</script>
This way, there is a socket opened between HTTP server and TCP server in Node.js.
If you need to communicate server-server than websockets is probably not a best choice. Try one of RPC libraries, or just use HTTP or your own protocol.
You can use either socket.io or ws (only WebSocket) on Node.js as client (not only in browser)
var io = require('socket.io-client');
var socket = io.connect('http://IP address of Websocket server');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});

Resources