我試圖讓兩個不同的節點進程(使用集羣)嘗試成爲服務器端口。但是,每當第二個進程到達端口時,它都不會檢測到該端口正在被使用。Node.js進程不檢測端口已被使用
我懷疑他們沒有檢測到端口是否打開的原因是由於回調的本質(我正在檢測端口是否使用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');
});
}
這裏是輸出:
因此,第一個過程(在這種情況下處理9120)變爲在端口1337的服務器,但那麼第二個進程沒有檢測到端口正在被使用,並以某種方式成爲服務器(我期望在這裏EADDRINUSE,不知道爲什麼它沒有顯示任何錯誤)。
任何幫助或澄清爲什麼這不起作用將不勝感激。
感謝,
我不是羣集專家,但我相信這是按預期工作的。如果您願意,集羣節點進程工作人員可以收聽相同的端口。主流程是實際綁定的流程,而其他人只是在聽。更多信息請訪問:https://nodejs.org/api/cluster.html –