React Native中使用Mqtt

環境:

1,在項目中安裝包

npm install react-native-native-mqtt --save

 項目GitHub地址 https://github.com/davesters/rn-native-mqtt

2,在本地搭建Mqtt服務器

這裏使用的EMQ來搭建Mqtt服務器

EMQ官網:https://www.emqx.io/cn/

點擊右上角的免費試用

然後下載Windows版,也有其他操作系統的,都可以在官網找到安裝方法

下載完成之後,解壓到沒有中文的路徑中

現在還不能直接使用,需要下載License

在下載的下面有

 我們使用免費30天的測試就可以了,如果需要正式使用,需要購買企業版或者公司服務器上自己搭建一個Mqtt服務器

下載完成之後將License中的所有文件放到emqx\bin目錄下

然後在bin目錄下打開命令行(可以在bin目錄下按住shift然後點擊鼠標右鍵),選擇在此處打開PowerShell窗口

然後運行  .\emqx start開啓服務,注:  .\emqx stop 關閉服務

然後在瀏覽器中訪問http://127.0.0.1:18083 應該就可以進入控制檯界面

賬號默認爲:admin

密碼默認爲:public

3,在RN程序中創建會話,發佈者和訂閱者(參照react-native-native-mqtt)這個包中的寫法

這裏的192.168.1.9 請替換成自己電腦的IP地址,且需要保證測試Android設備和電腦在同一個無線網絡下,

如果無法連接至服務器,可能是防火牆的問題,需要把電腦的防火牆打開

import React, { Component } from 'react';
import {
  View,
  Text
} from 'react-native';
import * as Mqtt from 'react-native-native-mqtt';
import { Buffer } from 'buffer'

const client = new Mqtt.Client('tcp://192.168.1.9:1883');

class BottomPage2 extends Component {
  constructor(props) {
    super(props);
    this.handlePublic = this.handlePublic.bind(this);
  }
  render () {
    return (
      <View>
        <Text onPress={this.handlePublic} style={{ fontSize: 65 }}>發佈信息</Text>
      </View>
    )
  }

  componentDidMount() {
    this.handleMqttStart();
  }

  componentWillUnmount() {
    this.handleMqttClose();
  }

  handleMqttStart() {
    client.connect({
      clientId: '1001',
      username: "ReSword",
      password: "0831"
    }, err => {
      console.log(err);
    });

    client.on(Mqtt.Event.Message, (topic, message) => {
      console.log('Mqtt Message:', topic, message.toString());
    });
    
    client.on(Mqtt.Event.Connect, () => {
      console.log('MQTT Connect');
      client.subscribe(['Test'], [0]);
    });
  }

  handleMqttClose() {
    client.disconnect();
    client.close();
  }

  handlePublic() {
    const buf = Buffer.from('runoob', 'ascii');
    client.publish("Test", buf);
  }

}

export default BottomPage2;

點擊發布信息

就可以收到來自本機的信息了

參考文章:

https://www.jianshu.com/p/e5cf0c1fd55c

https://www.runoob.com/w3cnote/mqtt-intro.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章