Flutter MQTT客户端的集成

转自:https://blog.csdn.net/weixin_44042238/article/details/100376563  

1.库 https://pub.dev/packages/mqtt_client
2.在pubspec.yaml文件中依赖mqtt_client: ^5.5.4

关键API

  • MqttClient客户端的初始化
//server 服务器地址
//clientIdentifier 客户端标识 (具有唯一性,如果两个客户端有相同的标识则两个客户端无法同时连接到服务器)
//port 端口
MqttClient.withPort(this.server, this.clientIdentifier, this.port);
  • 连接
//用户名跟密码 可选参数
Future connect([String username, String password])
  • 订阅一个主题
//topic 需订阅的主题
//qosLevel 常用三种类型 atMostOnce atLeastOnce exactlyOnce
Subscription subscribe(String topic, MqttQos qosLevel) 
  • 发布一个主题
//topic 发布的消息所属的主题
//qualityOfService 跟上面的 qosLevel 一样
//data 所需要发送的数据 
//retain 不知道
 int publishMessage(String topic, MqttQos qualityOfService, typed.Uint8Buffer data,{bool retain = false})
  • 消息回调
    当接收到消息的时候会在这里给出通知
Stream>> updates;
  • 开撸
import 'package:mqtt_client/mqtt_client.dart';
import 'package:typed_data/typed_buffers.dart';

class Mqtt {
  String server = 服务器地址;
  int port=端口号;
  String clientIdentifier=客户端标识;
  String subTopic = 需要订阅的topic;
  String publishTopic= 发送消息的topic;
  MqttQos qos = MqttQos.atLeastOnce;
  MqttClient mqttClient;
  static Mqtt _instance;

  Mqtt._() {

    mqttClient = MqttClient.withPort(server, clientIdentifier, port);

    ///连接成功回调
    mqttClient.onConnected = _onConnected;

    ///连接断开回调
    mqttClient.onDisconnected = _onDisconnected();

    ///订阅成功回调
    mqttClient.onSubscribed = _onSubscribed;

    ///订阅失败回调
    mqttClient.onSubscribeFail = _onSubscribeFail;

  }

  static Mqtt getInstance() {
    if (_instance == null) {
      _instance = Mqtt._();
    }
    return _instance;
  }
  ///连接
  connect() {
    mqttClient.connect();
    _log("connecting");
  }
  ///断开连接
  disconnect() {
    mqttClient.disconnect();
    _log("disconnect");
  }

  ///发布消息
  publishMessage(String msg) {
    ///int数组
    Uint8Buffer uint8buffer = Uint8Buffer();
    ///字符串转成int数组 (dart中没有byte) 类似于java的String.getBytes?
    var codeUnits = msg.codeUnits;
    //uint8buffer.add()
    uint8buffer.addAll(codeUnits);
    mqttClient.publishMessage(publishTopic, qos, uint8buffer);
  }

  ///消息监听
  _onData(List> data) {
    Uint8Buffer uint8buffer = Uint8Buffer();
    var messageStream = MqttByteBuffer(uint8buffer);
    data.forEach((MqttReceivedMessage m) {
      ///将数据写入到messageStream数组中
      m.payload.writeTo(messageStream);
      ///打印出来
      print(uint8buffer.toString());
    });
  }

  _onConnected() {
    _log("_onConnected");
    ///连接成功的时候订阅消息
    mqttClient.subscribe(subTopic, qos);
  }

  _onDisconnected() {
    _log("_onDisconnect");
  }

  _onSubscribed(String topic) {
    _log("_onSubscribed");
    ///在订阅成功的时候注册消息监听
    mqttClient.updates.listen(_onData);
  }
  
  _onSubscribeFail(String topic) {
    _log("_onSubscribeFail");
  }


  _log(String msg) {
    print("MQTT-->$msg");
  }
}

 

你可能感兴趣的:(Flutter开发)