Reputation: 1931
I'm building a simple chat room using TCP connection and node.js. I'm expecting the text to be transmitted after "Enter", but what's happened instead is that each character is sent immediately after pressing it. Here is my code...
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 --;
});
});
Upvotes: 0
Views: 986
Reputation: 3470
It sounds that telnet send each character by its own TCP request.
I recommend a different approach in which you listen on the sockets that created on each connection. This way in the future you will be able to manage each socket by its own and not from central location which may become tedious:
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);
});
});
Upvotes: 1