簡體   English   中英

node.js websocket聊天以處理平行顏色

[英]node.js websocket chat to handle parallel colors

我正在做一些需要聊天應用程序的項目。 我決定在此處測試一些node.js / websocket版本: http : //martinsikora.com/nodejs-and-websocket-simple-chat-tutorial

一切都完美,但是正如他在本教程結尾提到的那樣:

與Apache不同,Node.js並不為每個連接使用進程。

這意味着在7位用戶登錄后,將使用每種硬編碼顏色,然后將白色用作用戶名樣式。

// 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.');

是否可以允許兩個用戶使用相同的顏色? 謝謝

您最好只是在每個請求上隨機選擇一種顏色(這意味着您不必預先對colors數組進行隨機組合)。 是的,這意味着有時兩個連續的用戶將獲得相同的顏色; 那是真正隨機性的固有屬性,而不是人們錯誤地想象隨機性是什么。

您不應該使用Array.shift(),因為它會從colors數組中刪除一個元素,因此基本上在7個用戶之后,您的數組為空。

只是生成一個隨機ID

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

完成后:

usercolor = colors.shift();

添加此行:

colors.push(usercolor);

這會將返回的顏色放回另一端的數組中。 最終結果是它將一遍又一遍地循環顯示您的七種顏色。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM