What is mqtt?
MQTT is a lightweight transmission protocol, which is designed for lightweight publish / subscribe message transmission. MQTT protocol is specially optimized for low bandwidth networks and low computing power devices. It is a simple, stable, open, lightweight and easy to implement message protocol. It has wide applicability in information collection, industrial control, smart home and so on.
Who publishes and who subscribes?
MQTT The server is similar to a bulletin board, in which various advertisements are posted. Zhang San ran over and said that all those involved in football(/public/TEST/Soccer)Send all to yourself (subscribe) The next day, Li Si came to post an advertisement with the theme of(/public/TEST/Soccer),The content released is "competition on the 30th" At this time, the bulletin board will automatically send a text message to Zhang San, and the message sent is "there is a game on the 30th" Zhang San: APP End; Li Si: equipment end; Bulletin board: cloud MQTT The server
mqtt advantages?
1. MQTT is simpler:
MQTT is a message queuing protocol. It uses publish / subscribe message mode to provide one to many message publishing and decouple applications. Compared with other protocols, the development is simpler;
2. MQTT network is more stable
Work on TCP/IP protocol; Stable network connection is provided by TCP/IP protocol;
3. Lightweight
Small transmission, low overhead (fixed length header is 2 bytes), and protocol switching is minimized to reduce network traffic; Suitable for applications with low bandwidth and small amount of data;
What is the difference between MQTT and Websocket?
-
MQTT is a TCP based Pub/Sub protocol designed for the Internet of things scenario. It has many features optimized for the Internet of things, such as QoS, hierarchical themes, last words and so on.
-
WebSocket is a protocol designed for HTML5 applications to facilitate two-way communication with the server. HTTP handshake and then transfer to TCP protocol are used to replace the old implementations such as Server Push, Comet and long polling. All of the two intersect because of an application scenario: how to use HTML5 applications as MQTT clients to receive device messages or send information to devices, so MQTT over WebSocket naturally becomes the most reasonable way.
How to apply mqtt to realize chat function?
- First, let's start with the front-end layout style
In order to scroll to the latest news from time to time, we use the scroll view tag to wrap it. Using its scroll into view attribute, we bind a custom id
As shown in the figure:
We bind an id attribute to the created element, and scroll view can automatically scroll to its corresponding position.
The above is the display of several different message types. Let's not consider the style of types first. Let's realize the layout of left and right distribution of chat
It is recommended that you use flex layout to implement
Left doctor: display: flex;justify-content: flex-start; (default attribute)
Right patient: display: flex;justify-content: flex-end; (tail alignment)
In terms of style, these two attributes are mainly used. Other message types can be modified on this basis.
- Connect mqtt
First, we need to introduce dependencies
var Paho = require('./utils/paho-mqtt-wx.js')
var Paho = require('./utils/paho-mqtt-wx.js') /** * Connect mqtt */ connectMqtt() { // let t = 'abnormal disconnection'; var t = {} t.i = this.globalData.connectParams.msgTopicName t.c = 0 t.t = 3 // console.log(t, 98) const message = new Paho.Message(JSON.stringify(t)) this.connectOptions = {} //Connection mqtt user name this.connectOptions.userName = api.mqttuser //Connection mqtt password this.connectOptions.password = api.mqttpass //Will message a will message sent to the relevant subscriber when the client is disconnected this.connectOptions.willMessage = message //Heartbeat hold time is a long connection mechanism for MQTT. this.connectOptions.keepAliveInterval = 10 //Do you want to clear session when disconnecting this.connectOptions.cleanSession = this.globalData.connectParams.cleanSession //Sets whether the client automatically attempts to reconnect to the server if the connection is lost this.connectOptions.reconnect = false //Connection success callback this.connectOptions.onSuccess = this.onConnect //Connection failure callback this.connectOptions.onFailure = this.failConnect this.client = new Paho.Client('wss://' + this.globalData.connectParams.dnHost + '/mqtt', this.globalData.connectParams.clientId) //Called when the client loses connection this.client.onConnectionLost = this.onConnectionLost this.client.onMessageArrived = this.onMessageArrived //Establish a connection with the server this.client.connect(this.connectOptions) }, onConnect(){ console.log('Connection succeeded - onSuccess') //subscribe this.client.subscribe(this.globalData.connectParams.msgTopicName) //subscribe // var t = 'online'; var t = {} t.i = this.globalData.connectParams.msgTopicName t.c = 0 t.t = 0 const message = new Paho.Message(JSON.stringify(t)) message.destinationName = this.globalData.connectParams.statusTopicName //Send online message this.client.send(message) } failConnect(){ // Connect from New console.log('connection failed - onFailure') } onMessageArrived(message){ console.log('mqtt Message arrival - onMessageArrived:', message) } onConnectionLost(response){ // Connect from New console.log('mqtt Lost connection - responseObject:', response) }
Above, we complete the mqtt connection operation and some event listening.
Send messages and chat record cache processing?
This is already the core of the chat function
The first is message grouping. Messages are cached according to the sending time period. The idea of implementation is probably when we send or receive messages
We only need to compare the current message sending time (endTime) you want to send or you accept with the latest message recorded in our local cache
//Take a chestnut //Sending time of the latest message let newEndtime = 1624418176356, //Local cache latest message sending time oldEndtime = 1624418212889 //120000 (MS) 2 minutes newEndtime - oldEndtime <= 120000 ? Create new group: adds a message to the current group
This is the implementation idea of time grouping. We only need to calculate according to the message sending time to judge whether it is a message within two minutes. If it is a new message in the current message packet (messageArr[messageArr.length-1].messages.Push), if it is more than two minutes, we will directly create a new packet, that is, messagearr Push, just update the latest message to the local history message.
Pull up and load historical messages?
Local storage data and server data are mixed loaded. Due to the limitation of local storage of small programs, we only store 100 chat data in the front end. After the local data is loaded, we will call paging to obtain historical messages,
Note: for the paging of historical messages, there will be a paging parameter, that is, our messageArr message records the endTime (sending time) of the last message, and then combines the historical messages returned by the server into our messageArr. The overall message loading is based on these logic,
In the above steps, we can realize a basic chat function. The idea is generally like this. Students with questions can confide in me