Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

chatserver in node.js fundamental error

chatserver in node.js fundamental error


Hello i am running a basic code for a chatserver on node.js. This is almost lifted from the book - Node:Up and Running. The problem is when a client types a message, his message is transmitted at each keystroke, than after a complete line and pressing enter, resulting in output like this - client1: (Sends) Hello Client2: (Recieves)>h>e>l>l>o

But This is how it SHOULD come Client2: (Recieves)>hello

What is happening here is messages are being transmitted at each keystroke, than after pressing enter. I lifted another example code from git by someone and same thing happened! here is my code :

var net = require ('net');
var chatServer = net.createServer(),
     clientlist =[];
chatServer.on('connection',function(client){ = client.remoteAddress+':'+client.remotePort;
client.write('Welcome '+ + '!\n');
function broadcast(message, client){
 for(var i=0;i

Here is the github example which yielded same results: GITHUB HOW TO CORRECT THIS BEHAVIOR?

Problem courtesy of: new_web_programmer


The server event data is fired every time a block of data is received. Probably it fires for every character from the client.

The solution would be to create, in the server's connection callback, a buffer string/array. The data callback adds the received data to that buffer. When the data contains a newline character, the buffer is broadcasted and emptied.

Solution courtesy of: Roemer


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

chatserver in node.js fundamental error


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription