Node.js w/ Socket.io - switch users function (allow and prevent writing)

I'm building something with node.js and socket.io which allows users to write in a textarea (pretty much like a tchat), but I need them to write alternately. Something like:

  • User 1 is writing. User 2 and User 3 can't write.
  • User 1 send the message.
  • User 1 can't write. User 2 is allowed to write. User 3 can't write.
  • User 2 send the message.
  • User 1 and User 2 can't write. User 3 is allowed to write.
  • User 3 send the message.
  • User 1 is writing. User 2 and User 3 can't write.
  • ... etc

For now, I have (on the client side) :

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

on the server side :

    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');
    })

which makes me on the client side again :

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

The problems are that when they connect on the app, new users have the permission to write, so the first round they can all write at the same time, and when they all have written, permission does not loop and nobody can write.

I thought maybe something exists inside node.js or socket.io which allows me to do this more simply (the way I did is probably not the best), or anything else, but since I'm a beginner and I found nothing on the web, I'm asking for your help.

Thank you !

p.s: please excuse my english it is not my first language :)

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.