2015-04-14 35 views
2

我正在使用node.js与集群模块为了创建多进程socket.io服务器。带有socket.io的Nodejs集群丢失连接

使用this例子中,我创建了以下服务器端应用程序:

服务器:

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); 
}; 

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

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

任何人都可以帮助我吗?

回答

1

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

当我们将套接字传递给子进程时,它既可以被读取也可以不被读取,在负载较重的情况下,套接字将被主服务器读取(这当然是解决问题)的更多变化,因此我们应明确要求停止从此套接字读取。

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

connection._handle.readStop(); 

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