【发布时间】:2015-09-02 17:02:23
【问题描述】:
我试图让两个不同的节点进程(使用集群)尝试成为端口的服务器。但是,每当第二个进程到达该端口时,它都不会检测到该端口正在被使用。
我怀疑他们没有检测端口是否打开的原因是由于回调的性质(我正在检测端口是否已使用或未使用 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 ,不知道为什么它没有显示任何错误)。
任何关于为什么这不起作用的帮助或澄清将不胜感激。
谢谢,
【问题讨论】:
-
我不是集群方面的专家,但我相信这是按预期工作的。如果您愿意,集群节点进程工作人员可以监听相同的端口。主进程是实际绑定的进程,而其他进程只是监听。更多信息在这里:nodejs.org/api/cluster.html
标签: javascript node.js asynchronous process port