Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discussion: Best way to implement a chatroom with node.js / socket.io?

I'm not really talking about the general chat app, but rather specifically about the chatroom implementation.

So in node.js/socket.io, I thought of two approaches

  1. Create an array for each chatroom, broadcast message to all users in array

  2. Broadcasts all messages to all users, on clients' PCs determine if they belong in chatroom, if so, accept the message.

The weakness in 1 is that eventually as you scale up you will flood the server's memory with array objects, and I using only about 80mb on my hosting.

The weakness in 2 is that broadcasting to everyone is costly eventually and flooding the clients' machines won't make them happy.

I'm sure there are better approaches on how to implement the chatroom, so that's why I'm asking you guys to help me. I'm looking for performance on the server-side first then client-side, and it must be scalable.

like image 397
Derek Avatar asked Oct 10 '22 23:10

Derek


1 Answers

Socket.IO 0.7+ introduced a rooms concept. This is probably the thing you are looking for.

io.sockets.on('connection', function (socket) {
  socket.join('room name');

  // broadcast the message to everybody in the room
  socket.on('chat message', function (data) {
    socket.broadcast.to('room name').emit('chat message', data);
  });

  socket.on('leave room', function (room) {
    socket.leave(room);
  });
});

So no need to manage your own array with users for specific rooms, socket.io has this build in.

like image 127
3rdEden Avatar answered Oct 18 '22 00:10

3rdEden