0

我正在用 node.js 和 socket.io 构建一些东西,它允许用户在 textarea 中编写(很像 tchat),但我需要他们交替编写。就像是:

  • 用户 1 正在写入。用户 2 和用户 3不能写入。
  • 用户 1 发送消息。
  • 用户 1无法写入。允许用户 2 写入。用户 3无法写入。
  • 用户 2 发送消息。
  • 用户 1 和用户 2无法写入。允许用户 3 写入。
  • 用户 3 发送消息。
  • 用户 1 正在写入。用户 2 和用户 3不能写入。
  • ... ETC

现在,我有(在客户端):

    var ucan;
    $('#txtform').submit(function(event){
       if(ucan){
         socket.emit('trigger', me);
         ucan = false;
       }
       $('#txtArea').attr('readonly','true');
       }
    })

在服务器端:

    socket.on('trigger', function(user){
      u = user.id + 1; // switch to next user since users[] (further)
                       // stores all the users with their ids
      if(u >= users.length){
        u = 0; // loop throug all users
      }
      io.sockets.socket( users[u] ).emit('turn');
    })

这让我再次站在客户端:

    socket.on('turn', function(){
      ucan = true;
      $('#txtArea').removeAttr('readonly');
    })

问题是在app上连接的时候,新用户有写权限,所以第一轮他们可以同时写,当都写完后,权限不循环,没有人可以写。

我想也许在 node.js 或 socket.io 中存在一些东西,它可以让我更简单地做到这一点(我所做的方式可能不是最好的),或者其他任何东西,但因为我是一个初学者,我在网络,我在寻求你的帮助。

谢谢 !

ps:请原谅我的英语不是我的母语:)

4

1 回答 1

0

Have it readonly by default, then on the server side when a user connects, if they are the only socket connected, emit the 'turn'. You should probably also handle the case where the person whose turn it is disconnects, at which point you should do your trigger and let someone else have control.

于 2013-05-06T21:35:45.453 回答