0

这是一个简单的 TCP-Server 压力测试。只要我们每个客户端只发送一条消息,一切都会按预期工作。但是当每个客户端发送两条消息时,服务器突然停止,没有异常或错误。那么这是一个错误还是一个功能?

var net = require("net");
var async = require("async");
var cluster = require("cluster");

// `ulimit -n` tells us that we can open max. 1024 files per process.
//  Creating a socket means opening a file so we are limited.
var CLIENTS = 1000;

// Here is the weird part:
// - sending one message per client works fine
// - sending multiple message per client sucks
var MESSAGES = 2;

var TOTAL = CLIENTS * MESSAGES;
var PORT = 1234;
var HOST = "127.0.0.1";

if (cluster.isMaster) {
  var count = 0;
  var start = new Date;

  var server = net.createServer(function(socket) {
    socket.on("data", function(data) {
      var t;
      count++;
      console.log("server received " + count + " messages");
      socket.write(data, function(err) { if (err) console.error(err); });
      if (count === TOTAL) {
        t = (new Date) - start;
        console.log("server received and sent " + count + " messages within " + t + "ms");
      }
    });
  });

  server.listen(PORT, HOST, function() { cluster.fork(); });

} else {

  var run = function(i) {
    var c = net.connect({ port: PORT, host: HOST }, function() {
      var tasks = (function() {
        var results = [];
        for (var x = 1; x <= MESSAGES; ++x) {
          results.push((function(x) {
            return function(next) { c.write("Hello server!", next); };
          })(x));
        }
        return results;
      })();

      async.series(tasks, function(err) {
        if (err) { console.error(err); }
      });

    });
  };
  for (var i = 1; i <= CLIENTS; ++i) { run(i); }
}

在 Linux 3.11、Node.js 0.10.21 上测试

4

1 回答 1

2

您假设.write从客户端调用两次会在服务器上触发data两次事件,而不考虑可能正在进行的任何缓冲将合并多个写入。

当调用回调时.write,它并不意味着它实际发送的消息,它意味着消息被放入某个内核缓冲区(当它被发送到服务器时可能包含多个消息)。

于 2013-10-27T15:59:00.077 回答