How to listen for Room events

时间:2015-05-08 09:55:12

标签: javascript node.js sockets socket.io

So to clarify, I know the client should send a message such as 'join-room' to the server for handling, and thats fine, and I know I can do the same for 'leave-room'.

What I want is to actually listen to the events themself, because say if a client disconnects, I need to send a message to the rooms affected, as when a client disconnects then they automatically leave all rooms.

So I want something like;

<script>
  var data_a = $("#inputA").val();
  var data_b = $("#inputB").val();
  $("#ab_list #li_a .val").html(data_a);
  $("#ab_list #li_b .val").html(data_b);
<script>

So that if the user closes the window (which disconnects the client, and then triggers all the rooms to be left) I can send a message out.

I am using the latest socket.io, with the redis adaptor.

Also;

What is the most efficient way to list all the rooms a particular socket is in, as technically I think the disconnect event should contain the client_id so I could do this manually.

The key thing is clarity and stability, although I am open to alternate approaches (must still use socket.io).

Thanks

1 个答案:

答案 0 :(得分:1)

因此,如果我正确理解了您的主要问题:您想要听取加入和离开实施本身的空间的事件,以便 socket.join(room_id)应该触发您想听的事件。

事情是文档不提及任何听取该事件的方式。实际上,the implementation itself在加入房间时没有显示触发事件的迹象。我的猜测是你必须实现join_room/leave_room系统来处理它。

对于子问题,套接字对象包含一个名为rooms的数组,使socket.rooms包含套接字当前所有的空间。

这可能就是你要找的东西:

socket.on('disconnect', function() { for(var room in socket.rooms) { //do stuff before the client close the connection and leave the rooms } });