Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to manage multiple chat rooms with socket.io?

What is the proper way to manage multiple chat rooms with socket.io?

So on the server there would be something like:

io.sockets.on('connection', function (socket) {
  socket.on('message', function (data) {
    socket.broadcast.emit('receive', data);
  });
});

Now this would work fine for one room, as it broadcasts the message out to all who are connected. How do you send messages to people who are in specific chat rooms though?

Add .of('/chat/room_name')? Or store an array of everybody in a room?

like image 541
Guy guy Avatar asked Jul 17 '11 01:07

Guy guy


People also ask

How many rooms can socket.io handle?

socket.io rooms are a lightweight data structure. They are simply an array of connections that are associated with that room. You can have as many as you want (within normal memory usage limits).

When should I use socket.io rooms?

js and Socket.IO. 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.

How do I find out how many users are in a socket.io room?

my socket.io version 1.3.5on('create or join', function (numClients, room) { socket. join(room); }); I use this code for get clients in room : console.

Does socket.io use a lot of memory?

Basic usage of socket.io causes incremental memory usage (about +4mb every second). Even when nothing is transmitting.


2 Answers

Socket.IO v0.7 now gives you one Socket per namespace you define:

var room1 = io.connect('/room1');
room1.on('message', function () {
    // chat socket messages
});
room1.on('disconnect', function () {
    // chat disconnect event
});

var room2 = io.connect('/room2');
room2.on('message', function () {
    // chat socket messages
});
room2.on('disconnect', function () {
    // chat disconnect event
});

With different sockets, you can selectively send to the specific namespace you would like.

Socket.IO v0.7 also has concept of "room"

io.sockets.on('connection', function (socket) {
  socket.join('a room');
  socket.broadcast.to('a room').send('im here');
  io.sockets.in('some other room').emit('hi');
});

Source: http://socket.io/#announcement

like image 103
Sơn Trần-Nguyễn Avatar answered Nov 15 '22 06:11

Sơn Trần-Nguyễn


Update: Both Now.js and Bridge are now dead, see now.js dead and bridge dead. Socket.io seems to have adopted the callback feature as of v0.9, which is a good step forward.

While it isn't directly Socket.io related, Now.js (a higher level abstraction ontop of Socket.io) supports groups - http://nowjs.com/doc

They have a multi-room-chat example in their offocial repo here: https://github.com/Flotype/now/blob/master/examples/multiroomchat_example/multiroomchat_server.js

like image 26
balupton Avatar answered Nov 15 '22 06:11

balupton