我正在尝试克服在单个端口上可以打开多少个TCP
协议连接的限制。所以我想到了一种方法来创建在不同端口上运行的服务器的多个实例,例如:
server_i1.js
server_i2.js
server_i3.js
server_i4.js
然后我可以有一个额外的文件server_route.js
来检查每个实例上建立的连接数,并将用户转发给人口较少的实例。我尝试使用集群构建一些东西但它似乎只在同一个端口上创建新进程。如何让所有用户连接到http://exmaple.com:3000
,然后将其转发到四个可能的端口之一[3001, 3002, 3003, 3004]
?
当前的服务器方法:
var cluster = require('cluster');
var numCPUs = require('os').cpus().length;
if(cluster.isMaster) {
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
});
} else {
var http = require('http'),
_io = require('socket.io'),
server = http.createServer();
server.listen('3000', 'example.com');
var io = _io.listen(server);
var connections = {},
msg_sent = 0;
io.on('connection', function(socket) {
connections[socket.id] = new Date().getTime();
socket.on('client-request', function(msg) {
msg_sent++;
});
socket.on('disconnect', function() {
delete connections[socket.id];
});
});
setInterval(function() {
console.log( 'Active connections: ', Object.keys(connections).length, 'Messages sent: ', msg_sent );
}, 1000);
}
答案 0 :(得分:1)
也许使用循环法?示例实现如下所示:
const ports = ["3001"," 3002", "3003"];
var current = 0;
io.on('connection', function(socket) {
socket.emit("redirect",ports[current]);
current = (current + 1) % ports.length;
});
在客户端,人们会做
(function start(port){
const socket = io("http://localhost:"+port);
socket.on("redirect", port => (socket.close(), start(port)));
//whatever
})(3000);