React 中 MQTT 协议的使用 [英] Usage of MQTT protocol in React

查看:186
本文介绍了React 中 MQTT 协议的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对如何做出反应并试图了解如何让 MQTT 使用它有点陌生.

我尝试遵循此处发布的代码示例:https://www.npmjs.com/package/mqtt-react

但没有成功.出于某种原因,它只是什么都不做.

这是我的代码:

App.js 类:

import React, { Component } from 'react';导入'./App.css';从 './PostMessage.js' 导入 PostMqtt;从mqtt-react"导入{连接器};类 App 扩展组件 {使成为() {返回 (<div className="应用程序"><PostMqtt/>

);}}导出默认值 () =>(<连接器 mqttProps="ws://test.mosquitto.org/"><应用程序/></连接器>);

PostMessage.js 类:

从'react'导入React;从'mqtt-react'导入{订阅};导出类 PostMessage 扩展 React.Component {发送消息(e){e.preventDefault();//MQTT客户端传递const { mqtt } = this.props;mqtt.publish('sensor', '我的消息');}使成为() {返回 (<button onClick={this.sendMessage.bind(this)}>发信息);}}导出默认订阅({主题:传感器"})(发布消息)

知道出了什么问题吗?谢谢!

解决方案

经过长时间的研究,我找到了解决方案.

上面的连接器通过网络套接字支持 MQTT.默认的 mosquitto MQTT 端口是 1883,它直接进入 MQTT 代理而不是通过 websockets,这就是它没有连接的原因.

解决方案是使用端口 8080,即MQTT over WebSockets,未加密"(根据 mosquitto 文档).

所以我所要做的就是更改以下行至它奏效了.

希望对某人有所帮助.

I'm kinda new to react and trying to understand how to make MQTT work with it.

i've tried to follow the code sample published here: https://www.npmjs.com/package/mqtt-react

but had no success. for some reason it's just don't do anything.

here's my code:

App.js class:

import React, { Component } from 'react';
import './App.css';
import PostMqtt from './PostMessage.js';
import {Connector} from "mqtt-react";

class App extends Component {
    render() {
        return (
            <div className="App">
                <PostMqtt/>
            </div>
        );
    }
}

export default () => (
    <Connector mqttProps="ws://test.mosquitto.org/">
        <App />
    </Connector>
);

PostMessage.js class:

import React from 'react';
import { subscribe } from 'mqtt-react';

export class PostMessage extends React.Component {

    sendMessage(e) {
        e.preventDefault();
        //MQTT client is passed on
        const { mqtt } = this.props;
        mqtt.publish('sensor', 'My Message');
    }

    render() {
        return (
            <button onClick={this.sendMessage.bind(this)}>
                Send Message
            </button>
        );
    }
}

export default subscribe({
    topic: 'sensor'
})(PostMessage)

Any ideas what goes wrong? thanks!

解决方案

after long research i've found out the solution.

the connector above supports MQTT over web sockets. the default mosquitto MQTT port is 1883 which goes directly to MQTT broker and not via websockets, and that's why it didn't connect.

the solution is to use port 8080 which is "MQTT over WebSockets, unencrypted" (according to the mosquitto documentation).

so all i had to do is change the following row from to and it worked.

hope it helped someone.

这篇关于React 中 MQTT 协议的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆