请教这段代码cluster worker和net模块一起使用为何会出现阻塞?
发布于 9 年前 作者 gastrodia 3976 次浏览 最后一次编辑是 8 年前 来自 问答

很神奇的是,在master里直接调用socketHandler的话ab测试下不会阻塞

在worker里调用,ab测试并发数为1的时候不会阻塞

但像下面这样写,ab测试

ab -n 10 -c 2 http://localhost:10086

请求直接就阻塞了。。。

var net = require('net');
var http = require('http');
var cluster = require('cluster');

var recevice_socket_count = 0;
var recevice_http_count = 0;

var httpServer = http.createServer(function(req,res){
    console.log('recevice_http_count',++recevice_http_count);
    res.write('wow');
    res.end();
});

function socketHandler(socket){
  console.log('recevice_socket_count',++recevice_socket_count);
  socket.readable = socket.writeable = true;
  httpServer.emit('connection',socket);
  socket.emit('connect');
}


if(cluster.isMaster){
  var worker = cluster.fork();
  net.createServer(function(socket){
    worker.send("socket", socket);
    //socketHandler(socket);
  }).listen(10086, function() {
    console.log('netServer bound');
  });
}else{

  cluster.worker.on("message", function(data, socket) {
        socketHandler(socket);
  });
}

6 回复

不是阻塞了,socket没有关闭导致的

@NoahZhang 请问如何关?

@NoahZhang 为什么在master里调用的时候就不会出问题呢?

-c为2时,可以尝试调用一下socket.end() 就不会出现超时的情况了,我再试一下其他的状况

我试了加了req.socket.end(),还是不行 应该不是socket没关。ab -n 10 -c 2 url 发起测试 收到了10个socket链接,但只产生了9个http链接

回到顶部