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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值