Peter
Peter

Reputation: 1275

How to fix Error: listen EADDRINUSE while using nodejs isn't working, what else can I do?

I know this question was asked already, but the solutions provided didn't work for me.

Here is the websocket server code

const https = require('https');
const fs = require('fs');
const path = require('path');

const WebSocket = require('ws');

let connectionsList = [];
/*
 
*/
var server = https.createServer({
    cert: fs.readFileSync(path.resolve(__dirname, '../cert/certificate.crt')),
    key: fs.readFileSync(path.resolve(__dirname, '../cert/private.key'))
}, function (request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});

wsServer = new WebSocket.Server({ server });

function originIsAllowed(origin) {
    // put logic here to detect whether the specified origin is allowed.
    return true;
}

wsServer.on('connection', function (connection) {
    
    //save new connections here
    connectionsList.push(connection);

    connection.on('message', function (message) {
   
        const data = JSON.parse(message) || null;
        
        if (data !== null && data.type === 'push') {
            connectionsList.forEach((connection, index) => {
               //Must Skip First Item This One Pumps Data To The Others
               if (index > 0) {
                   if (connection.state === 'closed') {
                        ConnectionsList.splice(index);
                     }
                  connection.send(JSON.stringify(data.message));
                }
            })
        }
    });
});

wsServer.on("error", function(err){
    
    console.log(err);
});

module.exports = server;

Here is the runner or starter

// A simple pid lookup
var exec = require('child_process').execFile;
const wss = require('./ws_server/wss');
const config = require('./config');

var fun = function () {
    const process = exec(`${config.EXE.PATH}/${config.EXE.NAME}`, function () {
        wss.close();
        fun();
    });

    //if process is created, then makea  websocket server
    if (process.pid != null && process.pid !== undefined) {
        try{
             wss.on('error', function(error){
                console.log(error);
            });
            wss.listen({port: config.PORT,host: config.HOST}, function () {
                console.log((new Date()) + ` Server is listening on port ${config.PORT}`);
            });
        }
        catch(err){
        
        }
    }
}
fun();

I keep having this error below even after I have checked and can't find anything using that port. I have tried all the approached mentioned from the here How to fix Error: listen EADDRINUSE while using nodejs?

but nothing seems to work for me, please can anyone explain to me what's really the problem here. I am using windows server to run this nodejs script. thanks

How to fix Error: listen EADDRINUSE while using nodejs?

Upvotes: 0

Views: 336

Answers (2)

I found the problem. It was a guess. I updated the Node.js version in the computer and after that Node connected to the port and to the db successfully

Upvotes: 0

Manuel Spigolon
Manuel Spigolon

Reputation: 12870

The issue is that the close is not awaited since:

  • wss.close is called
  • fun is executed in sync and the wss.listen execute before the closing has been completed

It should be necessary to run fun in the close callback

    const process = exec(`${config.EXE.PATH}/${config.EXE.NAME}`, function () {
        wss.close(function(){
          // now the server is closed
          fun();
        });
    });

Upvotes: 1

Related Questions