0

我正在使用 TCP 连接和 node.js 构建一个简单的聊天室。我期望文本在“Enter”之后传输,但实际上发生的是每个字符在按下后立即发送。这是我的代码...

var server = net.createServer(function(conn){
    console.log('\033[92m  new connection! \033[39m');
    conn.write('> welcome to \033[92mnode-chat\033[39m! \n'
    + '> ' + count + ' other people are connected at this time.'
    + '\n > please write your name and press enter: '
  );

  count ++;
  conn.setEncoding('utf8');
  conn.on('data', function(data){
        console.log(data);
  });

  conn.on('close', function(){
        count --;
    });
});
4

1 回答 1

1

听起来telnet通过自己的TCP请求发送每个字符。
我推荐一种不同的方法,您可以在每个连接上创建的套接字上进行侦听。这样,将来您将能够自己管理每个套接字,而不是从可能变得乏味的中央位置管理:

var server = net.createConnection(...
  ...
});
server.on('connection', function(socket, connection){
  //I'm adding a buffer to the socket although you might not need it (try to remove it and see what happened)
  socket.buf = '';
  var self = this; //Use it if 'this' does not work. (explanation why to do it will confuse here but if there is a need I will explain)
  //Create a listener for each socket
  socket.on('data', function(data){
    //Since telnet send each character in it's own we need to monitor for the 'enter' character
    if( (data=='\\r\\n') || (data=='\\n') ){
      console.log(this.buf);//If 'this' doesn't work try to use 'self'
      this.buf = '';
    }
    else //No 'enter' character thus concat the data with the buffer.
      this.buf += data;
  });
  socket.on('end', function(){
    //Socket is closing (not closed yet) so let's print what we have.
    if(this.buf && (this.buf.length > 0) )
      console.log(this.buf);
  });
});
于 2013-05-20T10:39:30.063 回答