带有socket.io的Nodejs集群失去连接

我在集群模块中使用node.js来创build多进程socket.io服务器。

使用这个例子,我创build了以下服务器客户端应用程序:

服务器:

var cluster = require('cluster'); // Start master process if (cluster.isMaster) { // Create slave workers (in this example there is only one) var worker = cluster.fork(); // Starts a server that will delegate the connection to the worker var routerServer = net.createServer(function(connection) { worker.send({type: 'new_connection'}, connection); }); routerServer.listen(443, "my-ip-address"); } else { // Start a server on random Port var slaveHttp = require("http").Server(); slaveHttp.listen(0, "localhost"); // Connect socket.io to the server var io = require('socket.io')(slaveHttp); io.on('connection', function (socket) { console.log("Connected"); }); // On server messsage (new connection) emit it to the server process.on('message', function(message, handle) { if (message.type == 'new_connection') { slaveHttp.emit('connection', handle); }; }); } 

客户:

 var io = require('socket.io-client'); function connect(index) { connection = io.connect("http://my-ip-address", { reconnection: true, reconnectionDelay: 1000, timeout: 3000, multiplex: false }); connection.on('connect', function (socket) { console.log(index + ': Connected'); }); connection.on('connect_error', function (e) { console.log(index + ': Connection Error: ' + e); }); connection.on('message', function () { console.log(index + ': Server message'); }); connection.on('disconnect', function () { console.log(index + ': disconnect'); }); } for (var i = 0; i < 10; i++) { setTimeout(function(index) { return function() { connect(index); } }(i), i * 5000); }; 

问题是,在上面的例子中的一些客户端设法连接到服务器和交换消息,但其他人失败超时,然后,我可以看到在服务器的控制台,它收到超时客户端的连接但由于某种原因,他们没有成功沟通。

如果我将服务器代码replace为相同的进程,则此代码完美运行。

谁能帮我?

我发现这是Node.js中的一个错误,问题是Node.js套接字中有自动读取机制,会自动读取每个新的套接字。

当我们将套接字传递给subprocess时,它可以被已经读取或者不被读取,在负载较重的情况下,套接字将被主服务器读取(这当然是套用问题)的更多变化,因此我们应该明确地要求停止阅读这个sockets。

下面这行是一个很好的解决方法(应该在worker.send调用之前添加):

 connection._handle.readStop(); 

来源: https : //github.com/joyent/node/issues/7905