I'm trying to build a message/chat system between users.
Following rules are main features of message system.
- Each user can send message to others and only one-to-one chat is accepted.(which means only two users can share messages). If there are users named A to Z, user A can send message to B to Z but all message are independent so it's like one to one chatting system. A, B and C can't have conversation in the same message box (chatting room)).
- Message should be sent/received in realtime which is why I decided to use Socket.io
- After user logged out, message history is saved so user can see it whenever he/she login again.
This is how I think it's going to work.
When user A login, server creates an unique room for user A by using unique identifier which is userId in req Token. So, every user join a room when they login.
io.sockets.on('connection', function (socket) { socket.on('join', function (data) { socket.join(data.userId); }); });
Now, other users can send message to user A in realtime. Of course user A can also send message to particular user and get msg in realtime.
io.sockets.in('userId').emit('msg', {msg: 'hi!'});
If user A want to send message to user B but, user B is currently not logged-in which means there's no room of user B, then the message sent by user A is saved in .txt file and filepath is saved in database.
Later when user B checks the message box, user B can see all message history by loading .txt file.
So, it can be realtime chatting if both user A and B is logged-in and also can be message system if one user is not logged-in.