首页 > 解决方案 > 如何修复错误:在使用 nodejs 时听 EADDRINUSE 不起作用,我还能做什么?

问题描述

我知道这个问题已经被问过了,但提供的解决方案对我不起作用。

这是websocket服务器代码

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;

这是跑步者或起动器

// 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();

即使在我检查过并且使用该端口找不到任何东西之后,我仍然在下面出现此错误。我已经尝试过这里提到的所有方法 如何修复错误:在使用 nodejs 时听 EADDRINUSE?

但似乎没有什么对我有用,请任何人向我解释这里真正的问题是什么。我正在使用 Windows 服务器来运行这个 nodejs 脚本。谢谢

如何修复错误:在使用 nodejs 时监听 EADDRINUSE?

标签: node.jswindows

解决方案


问题是不等待收盘,因为:

  • wss.close叫做
  • fun同步wss.listen执行,关闭前执行完成

fun在关闭回调中运行应该是必要的

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

推荐阅读