【问题标题】:node.js websocket chat to handle parallel colorsnode.js websocket 聊天来处理平行颜色
【发布时间】:2012-09-10 01:34:59
【问题描述】:

我正在做一些需要聊天应用程序的项目。我决定在这里测试一些 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.');

是否有可能允许两个用户使用相同的颜色? 谢谢

【问题讨论】:

  • 如果我使用 .indexOf() 而不是 .shift() 方法会发生什么?

标签: arrays node.js websocket chat process


【解决方案1】:

您最好在每个请求中随机选择一种颜色(这意味着您不必预先调整颜色数组)。是的,这意味着有时两个连续的用户会得到相同的颜色;这是真正随机性的固有属性,而不是人们错误地想象的随机性。

【讨论】:

    【解决方案2】:

    你不应该使用 Array.shift(),因为它会从你的颜色数组中删除一个元素,所以基本上在 7 个用户之后你的数组是空的。

    只生成一个随机id

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

    【讨论】:

      【解决方案3】:

      做完之后:

      usercolor = colors.shift();
      

      添加这一行:

      colors.push(usercolor);
      

      这会将返回的颜色放回另一端的数组中。最终结果是它会一遍又一遍地循环使用您的七种颜色。

      【讨论】:

        猜你喜欢
        • 2023-04-04
        • 1970-01-01
        • 2022-08-11
        • 1970-01-01
        • 2014-09-22
        • 1970-01-01
        • 2011-11-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多