在node.js中将数据从客户端传输到服务器

时间:2013-05-19 21:08:03

标签: node.js tcpclient

我正在使用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 --;
    });
});

1 个答案:

答案 0 :(得分: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);
  });
});