• Ionic 使用 MQTT


    Ionic 使用 MQTT

    Ionic 使用 mqtt ,有一个比较好用的插件,用起来还不错,记录一下下!
    网址:https://www.npmjs.com/package/ionic-mqtt

    插件安装

    npm install ionic-mqtt --save
    

    在 app.module.ts 里面导包注入依赖

    import { IonicMqttModule, MQTTService } from 'ionic-mqtt';
    
    @NgModule({
      ...,
      imports: [
        ...,
        IonicMqttModule
      ],
      providers: [
        ...,
        MQTTService
      ],
    });
    
    export class AppModule {}
    

    使用

    在需要使用 mqtt 的页面

    import { MQTTService } from 'ionic-mqtt';
    
    @Component({
      selector: 'page-home',
      templateUrl: 'home.html'
    })
    
    export class HomePage {
    
      private _mqttClient: any;
    
      private MQTT_CONFIG: {
        host: string,
        port: number,
        clientId: string,
      } = {
        host: "test.mosquitto.org",
        port: 8081,
        clientId: "mqtt",
      };
    
      private TOPIC: string[] = [];
    
      constructor(private mqttService: MQTTService) {
      }
    
      ngOnInit() {
        this._mqttClient = this.mqttService.loadingMqtt(this._onConnectionLost, this._onMessageArrived, this.TOPIC, this.MQTT_CONFIG);
      }
    
      private _onConnectionLost(responseObject) {
        // connection listener
        // ...do actions when connection lost
        console.log('_onConnectionLost', responseObject);
      }
    
      private _onMessageArrived(message) {
        // message listener
        // ...do actions with arriving message
        console.log('message', message);
      }
    
      ...
    
    
      // public function for sending and publishing mqtt messages
    
      public sendMessage() {
        console.log('sendMessage')
        this._mqttService.sendMessage(TOPIC, MESSAGE);
      }
    
      public publishMessage() {
        console.log('publishMessage')
        this._mqttService.publishMessage(TOPIC, MESSAGE);
      }
    
      ...
    
    }
    

    在这里插入图片描述

    可以了!

  • 相关阅读:
    nohub
    swoole聊天室
    swoole httpserver学习
    swore tcp服务学习
    ps查看命令
    nginx和php-fpm调用方式
    Unix/Linux环境C编程入门教程(1) Solaris 11 64bit环境搭建
    Unix/Linux环境C编程入门教程(1) Solaris 11 64bit环境搭建
    C语言入门(4)——常量、变量与赋值
    C语言入门(3)——对Hello World程序的解释
  • 原文地址:https://www.cnblogs.com/wjw1014/p/12516558.html
Copyright © 2020-2023  润新知