Reputation: 12388
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.
Upvotes: 5
Views: 3315
Reputation: 4416
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.
Upvotes: 5
Reputation: 48709
Now.js will make this much easier: http://nowjs.com/guide - their guide already has a how to, as well as their github repo https://github.com/Flotype/now/tree/master/examples/multiroomchat_example
Upvotes: -2
Reputation: 5912
I did something similar here:
http://davidgranado.com/demos/chat_shuffle/
You can test it out by opening up several windows and chatting with yourself since each instance is considered a person (it's my first node app).
The way it works is that every person is paired up with another person for a conversation. Effectively, everyone is in a two person room.
To get the messages across, I register the users as being associated with each other and only send it to the one partner chatter. This idea can easily be expanded out any number of people to associate the chatters. That way, you don't have to do a wasteful broadcast to everyone.
Upvotes: 1