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和交换消息,但是其他服务器超时失败,然后我可以在服务器的控制台中看到它收到超时客户端的连接,但由于某些原因,它们无法通信。
如果我将服务器代码替换为相同的进程,则此代码完美运行。
任何人都可以帮助我吗?