node.js websocket chat to handle parallel colors
Problem
I'm working on some project where I need some chat application. I decided to test some node.js/websocket version here: http://martinsikora.com/nodejs-and-websocket-simple-chat-tutorial
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
Solution
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] })
Discussion
View additional discussion.