Reputation: 3832
I have this small piece of code. I run it, and then connect with a Telnet client.
var net = require('net');
//create server
var server = net.createServer(function (conn) {
console.log('New connection!')
//Message to the one who connects.
conn.write (
'\n > Welcome to NODE-CHAT!'
+ '\n > ' + count + ' other people are connected at this time.'
+ '\n > Please write your name and press Enter: '
);
//When a connected user writes...
conn.on('data', function (data) {
console.log(data);
});
conn.setEncoding('utf8');
});
//Listen
server.listen(3000, function () {
console.log('Server listening on *:3000');
})
When connected i get the Welcome messages as expected... Then if i write something in the telnet client, it will immediately trigger the conn.on listener... Lets say i write "hi you" the output in the console will be:
h
i
y
o
u
I would like this messages to sent when it is "finished" instead whenever i type character. I guess i could store the data from the conn.on trigger in a string, and output this string when the '\n' character is typed.
But I'm wondering if this is the right way to do it. Is there a way to change what trigger the conn.on? Maybe so it will only trigger (that is output in this case... ) on certain characters?... namely the \n char.
Upvotes: 0
Views: 67
Reputation: 493
I don't see any problems in your code. The behavior you describe is related to the Telnet client that sends every keystroke, it does not wait for you to hit enter. If you are on Linux try sending data with wget o open a browser and type
http://localhost:3000/hiyou
and see if you get a complete string instead of one character.
Upvotes: 1
Reputation: 106746
TCP is a stream of data so you should not make any assumptions about how much data you will receive by calling .read()
or when listening for data
events.
If your input is newline delimited, then you will have to buffer until you see a newline. There could also be multiple newlines in one chunk passed to your data
event handlers too.
Upvotes: 2