Discussion: the best way to implement chat with node.js / socket.io?

I'm not talking about the general application of the chat, but specifically about the implementation in the chat.

So in node.js / socket.io I was thinking of two approaches

  • Create an array for each chat, broadcast message to all users in the array

  • The transmission of all messages to all users on client computers determines whether they belong in the chat, if so, accept this message.

The weakness in 1 is that in the end, when scaling, you flood the server memory with arrays, and I use only about 80 MB on my hosting.

The weakness in 2 is that broadcasting to everyone will be costly, and flooding customers' cars will not make them happy.

I am sure that there are more effective approaches to how to implement chat, so I ask you guys to help me. First, I look for performance on the server side, and then on the client side, and it should be scalable.

+5
source share
3 answers

Socket.IO 0.7+ introduced the concept of rooms. This is probably what 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 you do not need to manage your own array with users for certain rooms, socket.io has this assembly.

+5
source

I did something similar here:

http://davidgranado.com/demos/chat_shuffle/

, , ( node).

, . , .

, . , . , .

+1

All Articles