在node.js中将数据从客户端传输到服务器
问题描述:
我正在使用TCP连接和node.js构建一个简单的聊天室。我期待在“Enter”之后发送文本,但发生的是每个字符在按下后立即发送。这是我的代码...在node.js中将数据从客户端传输到服务器
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 --;
});
});
答
这听起来是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);
});
});
能告诉你在客户端的代码? –
我使用Telnet作为我的客户端。 – Misaki