1. Introduction to instant messaging

Instant messaging is a common requirement in application development. This article describes the key points of the design of instant messaging function based on the author’s work using FLutter to develop instant messaging requirements.

2. Important concepts

Instant messaging requires the coordination of the front and back ends to agree on message formats and content. This IM client requirement development uses the company’s existing background built based on socket. IO. The following describes some concepts involved.

2.1 the WebSocket protocol

WebSocket is a protocol for full duplex communication over a single TCP connection. The main difference between WebSocket and the traditional HTTP protocol is that the WebSocket protocol allows the server to actively push data to the client, while the traditional HTTP server can only send data to the client after the client actively requests. Before WebSocket, im mostly used long polling.

2.2 Differences between socket. IO and WebSocket

Socket. IO is not WebSocket. It just encapsulates WebSocket, Polling mechanism and other real-time communication methods into a general interface, and implements the corresponding code of these real-time mechanisms on the server side. That is, WebSocket is just a subset of socket. IO’s implementation of instant messaging. Therefore, the WebSocket client cannot connect to the socket. IO server, and of course the socket. IO client cannot connect to the WebSocket server.

2.3 Server Socket Messages

If you understand the server side socket message, you can also understand the server side instant messaging logic. Socket messages sent by the server can be divided into two types:

  1. Unsolicited messages from the server:

    For example, user A sends A message to user B. After receiving the message from user A, the server forwards the message to user B. The message received by user B’s client is actively sent by the server. Other common scenarios include the broadcast of gift messages that all platform users will receive in the live broadcast software.

  2. The server returns a message after receiving a client message:

    For example, in the long-link heartbeat mechanism, the client sends a ping message to the server, and the Pong message returned by the server after successfully receiving the ping message from the client belongs to the return message of the server. In other common scenarios, user A sends A message to user B. After receiving the message from user A, the server returns A message to client A for client A to know the status of sending the message and determine whether the message is successfully sent. In most scenarios, the server needs to return a message after receiving an unsolicited message from the client.

3. Client implementation process

Several design client im focuses.

3.1 Heartbeat Mechanism

The heartbeat is when the client sends a ping message and the server returns a PONG message. If the client does not send ping messages for a period of time, the client is considered disconnected and the server actively disables the socket connection. When the client sends a ping message and the server does not return a Pong message for a period of time, the server is regarded as disconnected and the client will start the reconnection mechanism.

3.2 Reconnection mechanism

The reconnection mechanism allows clients to initiate connections again. Common reconnection conditions are as follows:

  • The client sends a ping message and the server does not return Pong for a period of time.
  • The client network is disconnected. Procedure
  • The server disconnects.
  • The client fails to initiate a connection. Procedure

In extreme cases (client disconnection), frequent reconnection may waste resources. You can set the maximum number of reconnection times in a period of time. When the number of reconnection times exceeds a certain threshold, the client sleeps for a period of time.

3.3 Message Sending Process

  1. The message is stored in the local database with the send state set to wait.
  2. Sending socket messages.
  3. After receiving the socket message returned by the server, the local database wait status message was changed to success.

Matters needing attention:

When the message is stored in the local database, an ID needs to be generated and stored in the database and sent to the server. When the message is received, the server determines which message to update the local database according to the ID.

3.4 Message receiving process

3.5 Other Related

  • Sorting of chat page messages: used when querying a local databaseorder bySort by time.
  • Message list: it is also recommended to do local storage. When receiving a message, you need to check whether the local message list has a dialog box of the current message user. If not, insert it first, and update it if there is. Message list maintenance will not expand said, interested can see the code.
  • Image voice messages: Upload images and languages to a dedicated server (a variety of dedicated cloud storage servers). Sokcet messages and local storage transfer urls on the cloud server.
  • Multiplayer chat (group chat) : Basically the same logic as single-player chat. A session ID field needs to be added to the local database for discriminating bits. When opening a group, the data corresponding to the session ID is queried. Chat messages are no longer sent to whom, but in which group chat.

4. Client Flutter code

Post part of the code and complete the project on the author’s Github.

4.1 Heartbeat Mechanism

  heart() {
    pingTimer = Timer.periodic(Duration(seconds: 30), (data) {
      if (pingWaitTime >= 60) {
        socket.connect();
        pingWaitTime = 0; pingWaitTimer! .cancel(); ping(); }if(! pingWaitFlag) ping(); }); } ping() { debugPrint("ping");
    String pingData =
        '{"type":"ping","payload":{"front":true},"msg_id":${DateTime.now().millisecondsSinceEpoch}} ';
    socket.emit("message", pingData);
    pingWaitFlag = true;
    pingWaitTime = 0;
    pingWaitTimer = Timer.periodic(Duration(seconds: 1), (data) {
      pingWaitTime++;
      print(data.hashCode);
      if (pingWaitTime % 10= =0) debugPrint(pingWaitTime.toString());
    });
  }
	//pong
  if (socketMessage.type == PONG && socketMessage.code == 1000) {
        pingWaitFlag = false; pingWaitTimer! .cancel(); pingWaitTime =0;
      }
Copy the code

4.2 Local Database Design

The design of the database table is more important, understand the database design, read the code is no pressure.

      //The message listCREATE TABLE chatDetail (
         chat_id TEXT PRIMARY KEY,//The primary key from_id TEXT,//Sender to_id TEXT,//Recipient created_at TEXT, content TEXT,//Message content image TEXT,//UI display, user profile picture name TEXT,//UI display, user name sex TEXT,//UI display, user gender status TEXT,//Message status typeINTEGER.//Message type, picture/The text/Voice message chat_object_id TEXT//The chat object ID, the chat object for the current user, is the core of a series of local operations.)//Message column table tableCREATE TABLE chatList (
         cov_id TEXT,
         unread_count INTEGER,
         last_msg_text TEXT,
         last_msg_at TEXT,
         image TEXT,
         name TEXT,
         sex TEXT,
         chat_object_id TEXT PRIMARY KEY)
Copy the code

5. To summarize

Either Flutter technology or IOS/Android/Web. Once you’ve mastered the core development process of instant messaging, the different technologies are just API variations. Apis tend to be document-oriented, but engineers with a large front end or a specific platform still need to understand the core development process, so it doesn’t make sense to have several apis that do the same thing.

Demo written relatively simple, have a question can comment.

Github address of the project.