node.js - 如何修复错误:在使用 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?
解决方案
问题是不等待收盘,因为:
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();
});
});
推荐阅读
- docker - 无法在 ScyllaDB 上创建集群
- swift - SwiftUI 中已发布的计算属性未更新
- python-3.x - 如何用字典值替换 pd.Series 列表值
- asp.net-core - 我无法在下拉菜单结构中显示选定的文本
- python - TCP 服务器和 Tkinter
- html - Flask 使用单选按钮渲染 html
- gmail-api - Gmail API 是否提供任何标志来检测授权帐户上的密码更改?
- laravel - 如何使用axios(vuejs)在laravel中提交多个csv文件并通过laravel excel导入
- routes - 仅对内部资源使用 OpenVPN 连接
- json - Ember Data JSON API - 如何使用相关链接 URL 发出 PATCH 请求