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

node.js websocket chat to handle parallel colors

node.js websocket chat to handle parallel colors


I'm working on some project where I need some chat application. I decided to test some node.js/websocket version here:

everything works perfect, but as he mentions in the end of the tutorial:

Node.js unlike Apache doesn't use processes for each connection.

It means that after 7 users logged in, every hard coded color will be used and then it uses white color for username style.

// Array with some colors
var colors = [ 'red', 'green', 'blue', 'magenta', 'purple', 'plum', 'orange' ];
// ... in random order
colors.sort(function(a,b) { return Math.random() > 0.5; } );

 userName = htmlEntities(message.utf8Data);
 // get random color and send it back to the user
  userColor = colors.shift();
  connection.sendUTF(JSON.stringify({ type:'color', data: userColor }));
  console.log((new Date()) + ' User is known as: ' + userName
          + ' with ' + userColor + ' color.');

Is it somehow possible to allow two users to use the same color? Thanks

Problem courtesy of: CBeTJlu4ok


you shouldn't use Array.shift(), since it removes an element from your Colors array, so basicaly after 7 users your array is empty.

just generate a random id

var idx = Math.floor(Math.random()*colors.length)
({ type:'color', data: colors[idx] })
Solution courtesy of: supernova


View additional discussion.

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

Share the post

node.js websocket chat to handle parallel colors


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription