[WeChat Mini Program 7] Implementation method of real-time chat system in cloud development

The following introduces a method to implement a real-time chat system in WeChat applet cloud development.

Mainly divided into three steps:

Table of contents

Step One: Design and Implementation of Chat Interface

Step 2: Monitoring and display of real-time messages

Step 3: The test results are as shown in the figure (mobile phone and computer communication)


For reference, you can directly locate the corresponding steps for reference based on the existing problems.

Here are the specific steps:

Step One: Design and Implementation of Chat Interface

This step does not involve specific real-time chat content, but mainly the design and coding of the chat interface. Therefore, I will directly use the specific project interface as the display area to analyze it for everyone.

In the red area in the picture, one is the chat message display area. This area will display the messages sent by myself and the messages sent to me by the other party. One is a chat button to send messages. The specific code is very simple, so I won’t show it here.

Okay, let's take a look at the second step.

Step 2: Monitoring and display of real-time messages

The implementation of real-time messages mainly relies on the watch function provided in cloud development to monitor data updates in the database. As shown in the picture.

For specific function usage, please refer to the instructions in the WeChat applet documentation: Collection: Object | WeChat open documentation

The specific steps in the writing process are divided into two steps:

Step 1: Define the listening function doWatcher().

In this function, what we watch is the collection named 'chats' in the cloud database. We use the onChange event to determine whether the data in the collection 'chats' has changed. If there is a change, all users will receive the change in the cloud data. Notification (this notification is automatically sent to the client from the cloud). After receiving the message, the client determines the status of the data update based on the dataType. If it meets its own requirements, it can write its own here. logic. For the value of dataType, please refer to the official documentation. As shown in the picture.

Step 2: Start the listening function.

Enable the listening function where you need to start monitoring. Under normal circumstances, it will be placed in the page loading onload function.

Step 3: The test results are as shown in the figure (mobile phone and computer communication)

Console output:

Welcome to follow, like and collect. If you have any questions, please leave a message or join QQ communication: 3110689397.

おすすめ

転載: blog.csdn.net/m0_60318025/article/details/132895912