The Demo rendering
Scheme selection — MQTT
Before we start this article, let’s introduce our two main characters π€ͺ : MQTT :MQTT (Message Queuing Telemetry Transport) MQTT :MQTT (Message Queuing Telemetry Transport) The publish/subscribe protocol is a lightweight communication protocol based on the PUBLISH /subscribe model. It is built on TCP/IP and was published by IBM in 1999. The biggest advantage of MQTT is that it can provide real-time, reliable messaging services for connecting remote devices with very little code and limited bandwidth. There are several options for implementing IM functionality within a project. Why MQTT? π€ First of all, considering the multi-terminal consistency of our project, our project has multiple terminals, one of which has adopted MQTT scheme to successfully access and realize functions, and may open multi-terminal conversations in the future, so I also plan to adopt MQTTβ message push scheme in my own project. There is another important reason: MQTT has libraries! A library!
The MQTT Client access
Step1:MQTTAppConnectionState
The first thing you need to be clear about is the connection state of the MQTT. This section is easy to understand. The possible states of the MQTT are connected, disconnected, and connecting. Enumerate them all.
enum MQTTAppConnectionState { connected, disconnected, connecting }
Copy the code
Very good! Have completed the first step, the idea is gradually clear π
Step2:MQTTAppState
Now that we have the connection state of MQTT, what else is needed? What do we know about the purpose of the connected state? Of course we send and receive messages when the connection is successful, we stop sending and receiving messages when the connection is disconnected, and we want to know when we receive a message we want to know what message we have received. All we need is a class called MQTTAppState.
class MQTTAppState with ChangeNotifier{
MQTTAppConnectionState _appConnectionState = MQTTAppConnectionState.disconnected;
String _receivedText = ' ';
String _historyText = ' ';
void setReceivedText(String text) {
_receivedText = text;
_historyText = _historyText + '\n' + _receivedText;
notifyListeners();
}
void setAppConnectionState(MQTTAppConnectionState state) {
_appConnectionState = state;
notifyListeners();
}
String get getReceivedText => _receivedText;
String get getHistoryText => _historyText;
MQTTAppConnectionState get getAppConnectionState => _appConnectionState;
}
Copy the code
In this class you can see that we define our current message receivedText and our history message _historyText. We define these two messages. Our history message is actually a superposition, newline process. We add this new message to form a new historical message. We also define methods to manage MQTTAppConnectionState. The point! π© Our class has inherited ChangeNotifier, as those familiar with Flutter can guess, for the convenience of global state management. Yes, Provider technology solution is also used here.
Step3:MQTTManager
To add a feature, a library, you need to have a global governance mindset, otherwise you will make it hard to distinguish your UI from your business logic in a framework like Flutter. The purpose of MQTTManager here is to unify your IM sending and receiving and message subscription. As a global Manager class, the first thing we need to define is the constructor. The constructor usually places the necessary contents of a class. Here you need to have a basic understanding of MQTT, here I write you the answer.
MQTTManager({
@required String host,
@required String topic,
@required String identifier,
@required MQTTAppState state
}
): _identifier = identifier, _host = host, _topic = topic, _currentState = state ;
Copy the code
The most basic configuration of an MQTT includes host(host address), topic(subscription topic), identifier(user identity), and state(connection state). In fact, these are not difficult to understand if you think carefully. These are some basic configurations for us to send and receive messages and distinguish between recipients and senders. We also need an MQTT server! π§, also we need to add the basic configuration of the server
void initializeMQTTClient(){
_client = MqttServerClient(_host,_identifier);
_client.port = 1883;
_client.keepAlivePeriod = 20;
_client.onDisconnected = onDisconnected;
_client.secure = false;
_client.logging(on: true);
_client.onConnected = onConnected;
_client.onSubscribed = onSubscribed;
final MqttConnectMessage connMess = MqttConnectMessage()
.withClientIdentifier(_identifier)
.withWillTopic('willtopic') set a will message
.withWillMessage('My Will message')
.startClean()
.withWillQos(MqttQos.atLeastOnce);
_client.connectionMessage = connMess;
}
Copy the code
For such a simple server, we have already configured the basic configuration, such as port number, connection retention duration, etc. After all the information is configured, we can add some basic management methods to the Manager.
The use of MQTT
In our above unremitting efforts, the next everything seems to be logical, pinch to π , combined with our page knowledge. We can implement our MQTT connection through the Manager
_connectMQTT()
{
manager = MQTTManager(
host: "test.mosquitto.org",
topic: "flutter/amp/cool",
identifier: _userName,
state: currentAppState);
manager.initializeMQTTClient();
manager.connect();
}
Copy the code
Also, since we have integrated ChangeNaotifier, we can dynamically listen to the messages we subscribe to π¦, easily, two lines of code.
// Current message received
appState.getReceivedText
// All historical messages
appState.getHistoryText
Copy the code
Sending a message is also very simple, one line of code, done ~ π
mqttManager.publish(message);
Copy the code
The whole MQTT framework is completed, with a cool login page, with a similar wechat chat interface, the effect is very good.
The project address
You gave me your starπ! MQTT Demo
The end of the
In fact, this is just a simple IMPLEMENTATION of MQTT, you may encounter the problem of sending and receiving messages, although not obvious but also affect the user experience, what is the reason? π€¨ Because we forget our good friends — the back-end partners, in actual development, we need to cooperate with the back-end partners. Our IM strategy is often to send IM messages through the back-end interface, and encapsulate our listening part. I will continue to update the specific plan in the follow-up development process, please pay attention to oh ~ π€©