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
You're better off just randomly picking a color on each request (which means you don't have to pre-shuffle the colors array). Yes, that means that sometimes two consecutive users will get the same color; that's an inherent property of real randomness, rather than what people mistakenly imagine randomness to be.
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] })
After doing:
usercolor = colors.shift();
Add this line:
colors.push(usercolor);
This puts the returned color back into the array at the other end. The net result is it'll cycle through your seven colors over and over.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.