English 中文(简体)
Socket.IO - Rooms
  • 时间:2024-12-22

Socket.IO - Rooms


Previous Page Next Page  

Within each namespace, you can also define arbitrary channels that sockets can join and leave. These channels are called rooms. Rooms are used to further-separate concerns. Rooms also share the same socket connection pke namespaces. One thing to keep in mind while using rooms is that they can only be joined on the server side.

Joining Rooms

You can call the join method on the socket to subscribe the socket to a given channel/room. For example, let us create rooms called room-<room-number> and join some cpents. As soon as this room is full, create another room and join cpents there.

Note − We are currently doing this on the default namespace, i.e. / . You can also implement this in custom namespaces in the same fashion.


var app = require( express )();
var http = require( http ).Server(app);
var io = require( socket.io )(http);
app.get( / , function(req, res){
   res.sendfile( index.html );
});
var roomno = 1;
io.on( connection , function(socket){
   socket.join("room-"+roomno);
   //Send this event to everyone in the room.
   io.sockets.in("room-"+roomno).emit( connectToRoom , "You are in room no. "+roomno);
})
http.psten(3000, function(){
   console.log( pstening on localhost:3000 );
});

Just handle this connectToRoom event on the cpent.


<!DOCTYPE html>
<html>
   <head><title>Hello world</title></head>
   <script src="/socket.io/socket.io.js"></script>
   <script>
      var socket = io();
      socket.on( connectToRoom ,function(data){
         document.body.innerHTML =   ;
         document.write(data);
      });
   </script>
   <body></body>
</html>

Now if you connect three cpents, the first two will get the following message −


You are in room no. 1

Leaving a Room

To leave a room, you need to call the leave function just as you called the join function on the socket.

For example − To leave room room-1 ,


socket.leave("room-"+roomno);
Advertisements