我正在使用带有集群模块的node.js来创建多进程socket.io服务器。
使用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);
};
问题在于上面示例中的某些客户端设法连接到服务器并交换消息,但是其他客户端在超时时失败,更奇怪的是我可以在服务器的控制台中看到它收到了定时的连接-out客户但由于某种原因他们没有成功沟通。
如果我将服务器代码替换为相同的进程,则此代码运行完美。
任何人都可以帮助我吗?
答案 0 :(得分:1)
我发现这是Node.js中的一个错误,问题是Node.js套接字中有自动读取机制,它会自动从每个新套接字读出。
当我们将套接字传递给子进程时,它既可以被读取也可以不被读取,在高负载下,主机将读取套接字的更多更改(这当然是解决问题),因此我们应该明确要求停止从这个套接字读取。
以下行是一个很好的解决方法(应该在worker.send调用之前添加):
connection._handle.readStop();