Node.js无法处理多个tcp消息

时间:2013-10-27 13:09:58

标签: javascript node.js sockets tcp

这是一个简单的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

1 个答案:

答案 0 :(得分:2)

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

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