节点JS TCP服务器不立即刷新缓冲区中的数据

时间:2016-06-17 20:32:13

标签: node.js tcpserver

我有以下代码:

// Setting up the TCP:
var server = net.createServer(function(socket) {
console.log('Android Client connected');

socket.setNoDelay(true);

socket.on('data', function(data) {
  console.log(data.toString());
  var json = JSON.parse(data.toString());

  if(json.id == 1) {
    socket.world = findAnEmptyWorld();
    socket.player = socket.world.addPlayer(json.data);
    socket.player.socket = socket;

    tcpClients.push(socket);

    socket.write(JSON.stringify({id: 3, data: socket.player.toJSON()}));
    socket.pipe(socket);
  }
});
});

server.listen(4444, function() {
console.log("TCP server listening on port 4444");
});

当我写消息时,它被存储到缓冲区中,但只有在我关闭服务器后才刷新...我应该怎么做才能在写入后立即刷新缓冲区? (正如你所看到的,我尝试过将setNoDelay'变为真)

1 个答案:

答案 0 :(得分:0)

我应该在字符串结束后添加一个新行... f#?^& k .... 像那样

socket.write(JSON.stringify({id: 3, data: socket.player.toJSON()}) + "\n");