W
W
WebDev2020-03-30 13:11:59
JavaScript
WebDev, 2020-03-30 13:11:59

Pitfalls in chat development. How to decide?

I write a chat on node+socket.io.
I am writing for the first time. All the manuals superficially describe the very principle of message passing, but when I got to the implementation, I ran into several questions. Below are the questions themselves and the options for solving them that came to my mind.

A little about how I organized everything:

  • User logs in
  • Gets a list of chats along with messages from the database via ajax
  • Connects to socket.io
  • Sending and receiving messages from socket.io
  • Socket.io on the server is engaged in sending messages and writing them to the database


Question #1
What if the connection to socket.io fails for some reason?
For example, it fell off for 5 seconds. During this time, the user was sent several messages. After 5 seconds, the connection was restored.
The user did not receive the message, but they registered in the database.

Solutions:
1. When a user connects to websockets (onconnect event), he also passes the id of the last message he has there. Socket.io on the server accepts this id and makes a request to the database, checking if there are any new messages there.
2. When a user connects to websockets (onconnect event), he himself requests via ajax messages for all chats.
The first option is good because it will be a complete imitation of the fact that messages have just arrived (sound, notification, etc.). The second one seems to be easier.

Question #2
This question is about how I organized everything. Namely, in what sequence you need to download the list of chats with messages and connect to sockets.
In the current implementation, the client does not connect to sockets until it has downloaded the list of chats. Is it correct? This is done because if the user first connects to the socket, and then downloads the list of chats and messages, it is not clear what to do - by the time the list of chats and messages is loaded, the user can already receive several messages through the sockets.
Solution options:
1. Connect to sockets and get a list of chats and messages in parallel. And store them separately, and display a mixed list to the user. True, this list will have to be sorted and checked for duplicates. It will be very costly in terms of resources.

Please tell me the best way to do it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MagicMight, 2020-03-30
@MagicMight

Question #1 The second solution is suitable and universal. Since, for example, when opening a VKontakte page and finding unread messages there, we don’t hear notification sounds for each of them?)
Question #2. Why pull ajax when you plan to use sockets anyway? The list of chats can be returned by the onconnect event.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question