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
Create an array for each chatroom, broadcast message to all users in array
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With