Socket.IO clients to receive offline messages when coming back

The amount of code I would have to write would be fairly large to create a solution if I consider which db and it's config, and client. You basically have to persist your messages in a database. As messages come in you would have to write to your conversation object (or whatever is representing the chat messages between clients).

socket.on('say', function (data) {
    // pseudo code to save conversation
    // var conversation = db.getConversation();
    // conversation.addMessage(data.message);
    // conversation.save();
    if (data.to == 'all') {
        io.sockets.emit('message', data.message);
    } else { //to specific client
        clients[data.to].emit('message', data.message);
    }
});

Then you would have to get all messages from the database when a client joins.

socket.on('online', function (data) {
    if (!clients[data.username]) {
        clients[data.username] = socket;
    }
    // pseudo code to get messages and display to user on first load
    // var conversation = db.getConversation();
    // var messages = conversation.getLast10Messages();
    // messages.forEach(function(message) { 
    //     clients[data.username].emit('message', message);
    // });
    io.sockets.emit('message',  data.user + 'online now');
});

You can specify a unique id as username to every user , save it at the server side, or use username, you also have client id(socket id), then save them in an object, now for every user you have an object that contains (username or unique id ) and socket id, now its easy to save messages when user is offline and then send it to user. Before emitting every event, you can search for socket id in the connected sockets object of socket.if socket id exists, you can emit, else , you still have username, and you can save messages in database by username.

Remember that, you must send receiver object info(username or unique id , and socket id) in every emitting from the client


use message queue like RabbitMQ. whenever a message comes from socket write to receiver's queue and when the receiver joins he will pick it from the queue.