Why it's create localhost:5000 CLOSE_WAIT Node? - node.js

my server started with PORT 5000, and sometimes it show next error
Error: listen EADDRINUSE: address already in use :::5000
When I Check port 5000, I see what port :5000 use for Chrome. They pass away after time( 1 min ) but, it's create more problems, i don't check code with terminal, because after error not showing console.log?

I think that chrome is launched by some development tool. Because System apps can not take port number more that 1024. So you need to check if your IDE is launching it and then check how to change the port or you can follow this link to auto increment the port if given port is not available.
var portrange = 45032
function getPort (cb) {
var port = portrange
portrange += 1
var server = net.createServer()
server.listen(port, function (err) {
server.once('close', function () {
cb(port)
})
server.close()
})
server.on('error', function (err) {
getPort(cb)
})
}
Code from link

Related

Node server is not running and Now errors are shown in the terminal

I have a node server which when I run is not showing server is running at port 5000 for example. Also, I got 0 errors in the terminal.
My question is how to check for errors that are causing the server not to run ?
app
.listen(port, () => {
console.log(`Server is running at port: ${port}`);
})
.on('error', function (err) {
console.log(err);
});
Here is the code that I use to run to listen to requests.

Socketio not connecting on postman socket connection ui on localhost

Could not connect to localhost:3000
17:02:53
Error: Unexpected server response: 404
Handshake Details
Request URL: http://localhost:3000/socket.io/?EIO=3&transport=websocket
Request Method: GET
Status Code: 404 Not Found
My express server listen on 3000 port and socketio http on 443 port, i am able to connect socket by hosting this on ec2 instance and using ec2 ip with port number on postman socket connection ui, but on localhost connection always failed with above error on postman socket beta ui.
You need to call listen only once. If you pass your http/https server to express, app.listen() is enough. (except you want to listen on 2 different ports.. For testing, let's call it only once.)
For accessing it on localhost try setting it explicitly with the parameter hostname in app.listen().
Example:
async function startServer() {
const app = express();
const credentials = {key: key, cert: crt};
const httpsServer = createServer(credentials,app);
const io = socketIO(httpsServer);
await require('./loaders').default({ expressApp: app, socketIO: io });
// Let's only call listen once for testing purposes. If you call
// listen on the express app, your https server will automatically listen
// to the same configuration.
// httpsServer.listen(4000);
const port = 3000
const hostname = 'localhost'
// explicitly let the app listen on localhost. If hostname is not
// provided, it will take the first found ipv4 interface
app.listen(port, hostname, err => {
if (err) {
Logger.error(err);
process.exit(1);
return;
}
Logger.info(`
################################################
🛡️ Server listening on https://${hostname}:${port} 🛡️
################################################
`);
});
}
Now you should be able to connect your socket. If it still does not work try
to use http module instead of https for better isolating your problem.
Note that your server now only will be accessible using localhost and not over ip. Both may only be possible when running 2 server instances with different hostnames.
async function startServer() {
const app = express();
const credentials = {key: key, cert: crt};
const httpsServer = createServer(credentials,app);
const io = socketIO(httpsServer);
await require('./loaders').default({ expressApp: app, socketIO: io });
httpsServer.listen(443);
app.listen(config.port, err => {
if (err) {
Logger.error(err);
process.exit(1);
return;
}
Logger.info(`
################################################
🛡️ Server listening on port: ${config.port} 🛡️
################################################
`);
});
}
This is my app.ts file, I am using Ubuntu. so 443 port is not allowed, i changed this port to 4000, now the app listen on the 3000 and socket http server on 4000, but socketio not able to connect with socket url localhost:3000

Can't connect to Node server on Amazon EC2

Here's the app.js, the code is too long so that's why I'm showing this code only, there's no problem in other code I assume this is a network problem.
app.js
app.listen(8080, 'localhost', function () {
console.log('Express started on http://localhost:' + 8080 + '; press Ctrl-C to terminate.');
});
I don't get any response when i run lsof -i :8080. but I do get response when I run curl localhost:8080 on the server.
and I don't think there's any problem with security group. I allowed any ip to access to the instance as you can see below.
and here's actually how it looks like when I test public ip and localhost
ubuntu#:ip~/$ curl -v 18.217.107.76:8080
* Rebuilt URL to: 18.217.107.76:8080/
* Trying 18.217.107.76...
* connect to 18.217.107.76 port 8080 failed: Connection refused
* Failed to connect to 18.217.107.76 port 8080: Connection refused
* Closing connection 0
curl: (7) Failed to connect to 18.217.107.76 port 8080: Connection refused
ubuntu#ip:~/$ curl -v localhost:8080
I get response here!
I changed the code from
app.listen(8080, 'localhost', function () {
console.log('Express started on http://localhost:' + 8080 + '; press Ctrl-C to terminate.');
});
to
app.listen(8080, function () {
console.log('Express started on http://localhost:' + 8080 + '; press Ctrl-C to terminate.');
});
now it's working
This is what worked for me!!
In your security group you have added the rule HTTP which listens by default on port 80.
So basically if you have configured your node server to run on a port other than port number 80 (I was doing this mistake) and try to access the public DNS(EC2 public DNS can be found in instance description) on browser, connection refused error might come so what you can do is change the PORT value in the config to 80.
Your config.env will look like this
PORT=80
And in your server.js you can write
const PORT = process.env.PORT;
try {
app.listen(PORT, () => { console.log(`server running at port ${PORT}`) })
} catch (error) {
console.log(error)
}

Socket.io not working on aws with nodejs

I am trying to connect to socket on aws ec2 instance. For some reason I am not able to do so . My client side code is :
var socket = io.connect('http://ec2-MY-IP.us-west-2.compute.amazonaws.com:3000');
console.log(socket);
socket.on('connect', function(){
alert(socket.id); // 'G5p5...
});
socket.on('connect_error', function(){
console.log('Connection Failed');
});
I Always get "Connection Failed" In browser console
I have opened the port from the security group's Inbound section and when I use :
telnet ec2-MY-IP.us-west-2.compute.amazonaws.com 3000
It gives me output
Trying ...
Connected to ec2-MY-IP.us-west-2.compute.amazonaws.com.
Escape character is '^]'.
My server Side Code goes HERE :
const express = require('express');
const bodyParser= require('body-parser');
const app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(3000, () => {
console.log('listening on 3000');
});
MongoClient.connect('mongodb://ec2-MY-IP.us-west-2.compute.amazonaws.com:27017/userlogsdemo', (err, database) => {
if (err) return console.log(err)
db = database;
console.log("DB CONNECTED")
io.on('connection', function (socket) {
console.log("SOCKET CONNECTED")
socketobj = socket
socket.on('reloadtickets', function (data) {
connectedusers.forEach(function(v){
if(v.connecteduserid == data.target){
setTimeout(function () {
io.emit('reloadticketsok',data );
}, 100)
}
});
});
// WHEN SOMEONE IS DISCONNECTED
});
})
When I RUN "node server.js" It says "DB CONNECTED" but not "SOCKET CONNECTED".
Code with localhost:8080(ON my local machine not on aws) works properly. Is there Anything special required to be done on aws Ec2. Any suggestions will be appreciated . Thanks in advance
There are 2 things that you can check.
How you configured your security groups. Please verify once :
You should select 'Custom TCP Rule' Port Range 3000 (as per your code), Source you can select anywhere(for testing).
You should check whether port 3000 is opened on linux(aws) firewall. To allow you can run :
sudo iptables -I INPUT -p tcp --dport 3000 -j ACCEPT
Let's take a closer look at the above command. We know what the iptables is in the command, thats the binary or program itself, now let's look at the other options.
-I stands for insert. This will insert the rule at the top of the chain. You can also use -A for append, which will place the new rule at the end of the chain.
INPUT tells the iptables command which chain you want the rule entered into.
-p tcp tells the rule to match only packets using the TCP protocol.
--dport 80 says to match traffic headed for port 80, or http. --dport stands for destination port.
-j stands for JUMP to jump to the specified action or chain. In our case we are using -j ACCEPT so it will jump to the ACCEPT action and allow the traffic through.
You should be open your port for socket on which its running
Lets you are using port 8890
sudo iptables -I INPUT -p tcp --dport 8890 -j ACCEPT

nodejs v5.10.1 cannot get my host address anymore?

Why the latest version of nodejs (v5.10.1) cannot get my host address anymore?
express code:
var express = require('express');
var app = express();
// respond with "Hello World!" on the homepage
app.get('/', function (req, res) {
res.send('Hello World!');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log(server.address());
console.log('Example app listening at http://%s:%s', host, port);
});
result:
{ address: '::', family: 'IPv6', port: 3000 }
Example app listening at http://:::3000
It should be:
http://127.0.0.1
Any ideas how I can fix this?
I am on Linux.
Actually, maybe you will see something like
:80
and then
::80
actually this one have a pattern like this:
host:port IPv4
host::port IPv6
127.0.0.1:80 means that using IPv4, listening in 127.0.0.1 in port 80
:80 means that using IPv4 ,listening on all address in port 80
127.0.0.1::80 means that using IPv6, listening in 127.0.0.1 in port 80
and so on.
so, the ::3000 means listening to IPv6 in port 3000
These configuration was done under these variable
var host = server.address().address;
var port = server.address().port;
you can just change the value of these variable to "127.0.0.1" and "80" and see what happens, but most likely your machine still using IPv6 there, if you want to change to IPv4 for your machine, change the setting of your machine under:
Windows: control panel -> network and sharing center -> (your network) -> properties -> setup the IPv4
Linux: i dont have linux machine to test this, but the syntax should be using ifconfig or ipconfig depends on your linux, please refer for something like https://unix.stackexchange.com/questions/34093/static-ipv4-ipv6-configuration-on-centos-6-2
Mac: i dont have mac machine also, should be the same with linux so try to do the same also
I have the same problem, i solved it acessing like an array:
server.address()["port"]
Here a example:
export const onError = (server: Server) => {
console.log(server.address()["port"])
return (error: NodeJS.ErrnoException): void => {
let port: number | string = server.address()["port"];
if (error.syscall !== 'listen') throw error;
let bind = (typeof port === 'string') ? `pipe ${port}` : `port ${port}`;
switch(error.code) {
case 'EACCES':
console.error(`${bind} requires elevated privileges`);
process.exit(1);
break;
case 'EADDRINUSE':
console.error(`${bind} is already in use`);
process.exit(1);
break;
default:
throw error;
}
}
}

Resources