gpt4 book ai didi

javascript - Node.js 进程未检测到端口已被使用

转载 作者:行者123 更新时间:2023-12-02 15:44:12 27 4
gpt4 key购买 nike

我试图让两个不同的 Node 进程(使用集群)尝试成为端口的服务器。但是,每当第二个进程到达该端口时,它都不会检测到该端口正在被使用。

我怀疑他们没有检测端口是否打开的原因是回调的性质(我正在使用 portInUse 函数检测端口是否已使用,因此它是异步获取的,并且稍后可能会导致某种类型的冲突)。

这是代码:

var cluster = require('cluster');
var net = require('net');

var PORT = 1337;
var list = {};
var portIsBeingUsed = false;

// Variable that detects if the port is in use.
var portInUse = function(port, callback) {
var server = net.createServer(function(socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
});

server.listen(port, 'localhost');
server.on('error', function (e) {
callback(true);
});

server.on('listening', function (e) {
server.close();
callback(false);
});
};

if (cluster.isMaster) {
for (var i = 0; i < 2; i++) {
cluster.fork();
}

Object.keys(cluster.workers).forEach(function(id) {
console.log("I am running with ID : "+ cluster.workers[id].process.pid);
list[cluster.workers[id].process.pid] = 0;
});

cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
});
} else { // Rest of the logic with all Processes goes here.

// Get the Process ID of the current process in execution.
var pid = cluster.worker.process.pid;
console.log("This is process " + pid + " working now.\n");

// Verify if Port is being used.
portInUse(PORT, function(returnValue) {
if(returnValue) { // Become a Client to the Server
console.log("port " + PORT + " is being used.\n\n");
becomeClient(pid);
} else { // Become a Server
console.log("port" + PORT + " is not being used.\n\n");
becomeServer(pid);
}
});
}

function becomeServer(pid) {
var server = list[pid];

server = net.createServer(function (socket) {
socket.write('Hello Server 1\r\n');
socket.end("hello");
console.log("Someone connected to Server 1. \n");
socket.pipe(socket);
});

server.listen(PORT, function(){
console.log("Process " + pid + " has become the Server on Port " + PORT);
});

server.on("error", function() {
console.log("there was an error on Process " + pid);
console.log("this error was becoming a Server.");
});
}

function becomeClient(pid) {
var client = list[pid];

client = net.connect({port: PORT}, function() {
list[pid].write("I am connected to the port and my pid is " + pid);
});

client.on('data', function(data) {
console.log(data.toString());
list[pid].end();
});

client.on('end', function() {
console.log('disconnected from server');
});
}

这是输出:

enter image description here

因此,第一个进程(在本例中为进程 9120)成为端口 1337 上的服务器,但第二个进程没有检测到该端口正在使用,并且以某种方式也成为服务器(我希望这里有一个 EADDRINUSE ,不确定为什么它没有显示任何错误)。

任何关于为什么这不起作用的帮助或澄清将不胜感激。

谢谢

最佳答案

这是预期的行为,也是cluster 模块的工作方式(默认情况下)。它允许将同一端口的传入请求轻松地分配给可用的工作人员。

关于javascript - Node.js 进程未检测到端口已被使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32359067/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com