Giter VIP home page Giter VIP logo

mqtt-client-examples's Introduction

MQTT Client Examples

This repository contains examples of MQTT clients using the MQTT 3.1, 3.1.1, and 5.0 protocols. You can use these examples to learn about the MQTT protocol and how to use MQTT clients with any MQTT broker.

IMPORTANT SECURITY TIP: Before submitting any code changes, please change your username and password to "emqx/public" in the examples' configuration files. This will prevent any unintended access to your MQTT broker.

MQTT Broker for Testing

If you want to test these examples, you can use the MQTT broker provided by EMQ X at broker.emqx.io. Please note that this is a public broker and should not be used for production.

The broker supports the following protocols:

  • Broker: broker.emqx.io
  • TCP Port: 1883
  • WebSocket Port: 8083
  • SSL/TLS Port: 8883
  • WebSocket Secure Port: 8084

Regarding the CA certificate download link for the Free Public MQTT Broker, you can visit: https://assets.emqx.com/data/broker.emqx.io-ca.crt

Directory Structure

Each directory contains examples in the respective programming language. Examples are organized into folders, with each folder containing an example program. Please see the README file for each example program to learn how to run the example.

Contributing

If you have any suggestions or improvements regarding MQTT client examples, feel free to submit a pull request. Before submitting a PR, please make sure that you have tested your code and passed all test cases.

License

This repository is licensed under the MIT License. Please see the LICENSE file for more information

mqtt-client-examples's People

Contributors

0721betty avatar alvin1221 avatar benniu avatar catgok avatar chongyuanyin avatar h6w avatar hjianbo avatar imrob-s avatar jaylinyu avatar keynslug avatar kjellwinblad avatar leeway1208 avatar lucas-emqx avatar luoyq0629 avatar michonnehsu avatar oucb avatar ranmaoyi avatar savonarola avatar swilder-m avatar tigercl avatar wangqianyu6 avatar wivwiv avatar wuzufeng avatar xavier-hou avatar xinyi-xs avatar xl-yibai avatar ysfscream avatar yuyuebalabala avatar zhiw avatar zibuyu1995 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mqtt-client-examples's Issues

mqtt-client-React example does not work

Hello,

I tried to run the mqtt-client-React, and this is the error:

Error: error:0308010C:digital envelope routines::unsupported
    at new Hash (node:internal/crypto/hash:71:19)
    at Object.createHash (node:crypto:133:10)
    at module.exports (/mypath/git/mqtt-client-React/node_modules/webpack/lib/util/createHash.js:135:53)
    at NormalModule._initBuildHash (/mypath/git/mqtt-client-React/node_modules/webpack/lib/NormalModule.js:417:16)
    at /mypath/git/mqtt-client-React/node_modules/webpack/lib/NormalModule.js:452:10
    at /mypath/git/mqtt-client-React/node_modules/webpack/lib/NormalModule.js:323:13
    at /mypath/git/mqtt-client-React/node_modules/loader-runner/lib/LoaderRunner.js:367:11
    at /mypath/git/mqtt-client-React/node_modules/loader-runner/lib/LoaderRunner.js:233:18
    at context.callback (/mypath/git/mqtt-client-React/node_modules/loader-runner/lib/LoaderRunner.js:111:13)
    at /mypath/git/mqtt-client-React/node_modules/babel-loader/lib/index.js:59:103 {
  opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
  library: 'digital envelope routines',
  reason: 'unsupported',
  code: 'ERR_OSSL_EVP_UNSUPPORTED'
}

Node.js v18.13.0
error Command failed with exit code 1.

Android双向认证异常失败

java.lang.ClassCastException: org.bouncycastle.asn1.pkcs.PrivateKeyInfo cannot be cast to org.bouncycastle.openssl.PEMKeyPair 2024-05-15 17:17:40.484 31070-31070 System.err io.emqx.mqtt W at io.emqx.mqtt.SSLUtils.getSocketFactory(SSLUtils.java:70) 2024-05-15 17:17:40.484 31070-31070 System.err io.emqx.mqtt W at io.emqx.mqtt.Connection.getMqttConnectOptions(Connection.java:54) 2024-05-15 17:17:40.484 31070-31070 System.err io.emqx.mqtt W at io.emqx.mqtt.MainActivity.connect(MainActivity.java:48) 2024-05-15 17:17:40.485 31070-31070 System.err io.emqx.mqtt W at io.emqx.mqtt.ConnectionFragment$1.onClick(ConnectionFragment.java:53) 2024-05-15 17:17:40.485 31070-31070 System.err io.emqx.mqtt W at android.view.View.performClick(View.java:7201) 2024-05-15 17:17:40.485 31070-31070 System.err io.emqx.mqtt W at android.view.View.performClickInternal(View.java:7170) 2024-05-15 17:17:40.485 31070-31070 System.err io.emqx.mqtt W at android.view.View.access$3500(View.java:806) 2024-05-15 17:17:40.485 31070-31070 System.err io.emqx.mqtt W at android.view.View$PerformClick.run(View.java:27562) 2024-05-15 17:17:40.485 31070-31070 System.err io.emqx.mqtt W at android.os.Handler.handleCallback(Handler.java:883) 2024-05-15 17:17:40.485 31070-31070 System.err io.emqx.mqtt W at android.os.Handler.dispatchMessage(Handler.java:100) 2024-05-15 17:17:40.485 31070-31070 System.err io.emqx.mqtt W at android.os.Looper.loop(Looper.java:214) 2024-05-15 17:17:40.485 31070-31070 System.err io.emqx.mqtt W at android.app.ActivityThread.main(ActivityThread.java:7682) 2024-05-15 17:17:40.485 31070-31070 System.err io.emqx.mqtt W at java.lang.reflect.Method.invoke(Native Method) 2024-05-15 17:17:40.485 31070-31070 System.err io.emqx.mqtt W at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516) 2024-05-15 17:17:40.485 31070-31070 System.err io.emqx.mqtt W at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

use the MqttTwoWayTlsSample.java following error

i use the MqttTwoWayTlsSample.java and emqx owner ca in directory : etc/certs , but the following error occurred。
when i use the mqtt.fx tool ,is ok
the emqx version is 5.0.26。
Caused by: java.security.cert.CertificateException: No subject alternative names present
at sun.security.util.HostnameChecker.matchIP(HostnameChecker.java:150)
at sun.security.util.HostnameChecker.match(HostnameChecker.java:99)
at sun.security.ssl.X509TrustManagerImpl.checkIdentity(X509TrustManagerImpl.java:441)
at sun.security.ssl.X509TrustManagerImpl.checkIdentity(X509TrustManagerImpl.java:409)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:228)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:128)
at sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:636)

image

CERTIFICATE_VERIFY_FAILED - Flutter can not connect with SSL enable.

I used EQTTX tool to connect server with ssl enable it's successful but when I tested with sample code flutter then update owner server information it's not working.
Here I get my log:

flutter: 1-2024-05-24 15:34:33.404964 -- MqttConnectionHandlerBase::connect - server xx.x.xxx.xx, port xxxxx
flutter: 1-2024-05-24 15:34:33.406234 -- SynchronousMqttServerConnectionHandler::internalConnect entered
flutter: 1-2024-05-24 15:34:33.406363 -- SynchronousMqttServerConnectionHandler::internalConnect - initiating connection try 0, auto reconnect in progress false
flutter: 1-2024-05-24 15:34:33.406531 -- SynchronousMqttServerConnectionHandler::internalConnect - secure selected
flutter: 1-2024-05-24 15:34:33.406841 -- SynchronousMqttServerConnectionHandler::internalConnect - calling connect
flutter: 1-2024-05-24 15:34:33.407136 -- MqttSecureConnection::connect - entered
flutter: 1-2024-05-24 15:34:33.620473 -- MqttConnectionBase::_onError - calling disconnected callback
flutter: Exception: HandshakeException: Handshake error in client (OS Error: 
	CERTIFICATE_VERIFY_FAILED: application verification failure(handshake.cc:393))
flutter: 1-2024-05-24 15:34:33.621841 -- MqttConnectionHandlerBase::disconnect - entered
flutter: 1-2024-05-24 15:34:33.621990 -- MqttConnectionHandlerBase::_performConnectionDisconnect entered
flutter: Disconnected
flutter: EMQX client connection failed - disconnecting, status is Connection status is disconnected with return code of noneSpecified and a disconnection origin of solicited
flutter: Disconnected

And my code here
Screenshot 2024-05-24 at 15 45 13
Please help me to resolve my issues. Thanks

mqtt-client-Vue.js 中协议protocol端口,设置mqtt会自动转换为ws

问题(question):
我在一台机器人上部署了对应的mqtt服务器,我想使用 mqtt-client-Vue.js 案例调整参数来连接它,但出现无法连接的情况,我修改的参数如下图
test

test02

相同的,我通过MQTTX客户端来设置相同的参数,并且能成功连接上机器人来进行控制。但案例 mqtt-client-Vue.js 并没有解决我的问题,我通过console.log()方法打印protocol端口的信息竟然是ws协议,而不是我设置的mqtt协议。请问该如何解决?

mqtt3和mqtt5同时存在时,会出现接收消息解析失败的情况!!!

项目里要求同时连接mqtt3和mqtt5,如果先建立mqtt3成功,再建立mqtt5成功。此时再用mqtt3发送topic消息,再接收消息时,解析会使用mqtt5的payload里。看了代码里面的实现,在建立mqtt3或者mqtt5时,本地会存储mqtt版本号:
if let storage = CocoaMQTTStorage() {
storage.setMQTTVersion("5.0")
}
if let storage = CocoaMQTTStorage() {
storage.setMQTTVersion("3.1.1")
}
这是没有带clientid的,这样会导致谁后调用就会覆盖之前存储的mqtt版本号。
这样在收到消息解析payload时:
var protocolVersion = "";
if let storage = CocoaMQTTStorage() {
protocolVersion = storage.queryMQTTVersion()
}

    if (protocolVersion == "5.0"){
        let data = MqttDecodePublish()
        data.decodePublish(fixedHeader: packetFixedHeaderType ,publishData: bytes)
        pos += 1

        if(data.propertyLength != 0){
            pos += data.propertyLength!
        }

        // MQTT 5.0
        self.mqtt5Topic = data.topic
        self.packetIdentifier = data.packetIdentifier
        self.publishRecProperties = data

    }else{
        // MQTT 3.1.1
        topic = NSString(bytes: [UInt8](bytes[2...(pos-1)]), length: Int(len), encoding: String.Encoding.utf8.rawValue)! as String
    }

这样就会导致mqtt3发送的消息,会进入mqtt5的解析中。请确认如何修正

Connect failed! - in react native - AMQJS0007E

trying to use MQTT code in react native from the example provided

const options = {
host: 'broker.emqx.io',
port: 8083,
path: '/testTopic',
id: 'id_' + parseInt(Math.random()*100000)
};

Its returning me the error
Connect failed!
{"errorCode": 7, "errorMessage": "AMQJS0007E Socket error:undefined.", "invocationContext": undefined}

what could be the issue ?

按照文档设置tls双向认证不成功

按照文档: 生成了服务端和客户端证书
在控制台配置了服务端证书和根证书开启了客户端验证
image
使用mqttx工具配置客户端证书和根证书可以连接成功
image
使用java paho客户端按照列子 设置不成功

` Security.addProvider(new BouncyCastleProvider());

    // Load CA certificates
    KeyStore caKs = loadCAKeyStore(caCrtFile);

    // Load client certificate chain and key
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null, null);

    // Load the entire client certificate chain
    Certificate[] chain;
    try (FileInputStream fis = new FileInputStream(crtFile)) {
        CertificateFactory cf = CertificateFactory.getInstance("X509");
        Collection<? extends Certificate> certs = cf.generateCertificates(fis);
        chain = certs.toArray(new Certificate[0]);
    }

    // Load client private key
    try (PEMParser pemParser = new PEMParser(new FileReader(keyFile))) {
        Object object = pemParser.readObject();
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
        PrivateKey key = converter.getPrivateKey((PrivateKeyInfo) object);
        ks.setKeyEntry("private-key", key, password.toCharArray(), chain);
    }

    // Set up key managers and trust managers
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
    tmf.init(caKs);
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, password.toCharArray());

    // finally, create SSL socket factory
    SSLContext context = SSLContext.getInstance("TLSv1.2");
    context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    return context.getSocketFactory();`

反复检查了证书路径没有问题
请问下这个有什么方法处理吗

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

If I process the models model while subscribing to mqtt, it will result in django. core. exceptions. AppRegistryNotReady: Apps are not loaded yet

源码
mqtt.py
import paho.mqtt.client as mqtt
from common.ProductData.BaseData import BaseProductData
from .consumer import Consumer
import threading

class MQTTClient:
client = mqtt.Client(protocol=3)
BROKER = 'broker'
KEEPALIVE = 50
USER_NAME = 'root'
PASSWORD = '123'
PORT = 1883

def __init__(self):
    self.broker = self.BROKER
    self.port = self.PORT
    self.keepalive = self.KEEPALIVE
    self.username = self.USER_NAME
    self.password = self.PASSWORD
    # self.connect()

def on_publish(self, client, userdata, mid):
    print("消息发送成功")

def on_log(self, client, userdata, level, buf):
    print(f"MQTT log: {buf}")

def on_subscribe(self, client, userdata, mid, granted_qos):
    print("Subscribed with QoS " + str(granted_qos[0]))

def connect(self):
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
            self.client.subscribe(BaseProductData.subscribe_topic(), qos=1)
        else:
            print("Failed to connect, return code %d\n", rc)

    self.client.on_publish = self.on_publish
    self.client.on_log = self.on_log
    self.client.on_message = Consumer.on_message
    # self.client.on_subscribe =

    if self.username and self.password:
        self.client.username_pw_set(self.username, self.password)
    self.client.on_connect = on_connect

    # self.client.connect(self.broker, self.port, self.keepalive)
    self.client.connect_async(self.broker, port=self.port, keepalive=self.keepalive, bind_address="")

def publish(self, topic, msg):
    result = self.client.publish(topic, msg, qos=1)
    status = result[0]
    if status == 0:
        print(f"Send `{msg}` to topic `{topic}`")
    else:
        print(f"Failed to send message to topic {topic}")

# def subscribe(self, topic):
#     self.client.subscribe(topic)
#     # self.client.on_message = on_message
#     self.client.loop_forever()

def disconnect(self):
    self.client.loop_stop()
    self.client.disconnect()

def send_publish(self, msg):
    def on_publish(client, userdata, mid):
        print("消息发送成功")

    self.client.loop_start()
    self.client.on_publish = on_publish

    result = self.client.publish("/topic/send_msg", msg)
    status = result[0]
    if status == 0:
        print(f"Send `{msg}` to topic `/topic/send_msg`")
    else:
        print(f"Failed to send message to topic /topic/send_msg")

client = MQTTClient()
client.connect()

import json
from common import const
from common.views import RowDict
from apps.product.models import Product, ProductUser, ProductAutomation
from apps.scene.models import Scene
from django.core.cache import cache

class ProductHandleClas:
def init(self):
pass

@classmethod
def update_date(cls, *args, **kwargs):
    kwargs = RowDict(kwargs)
    product = Product.objects.filter(id=kwargs.product_id)
    product_user = ProductUser.objects.filter(product_id=kwargs.product_id, user_id=kwargs.user_id)
    if product and product_user:
        Product.objects.filter(id=kwargs.product_id).update(status=kwargs.status)
        print("处理完成")

class SceneHandleClas:

def __init__(self):
    pass

@classmethod
def update_date(cls, *args, **kwargs):
    pass
    kwargs = RowDict(kwargs)
    key = f"{kwargs.scene_id}{kwargs.user_id}"
    # 根据场景id查询
    scene = Scene.objects.filter(id=kwargs.scene_id, user_id=kwargs.user_id)
    if not scene:
        raise
    # 根据场景id查询自动化
    pa = ProductAutomation.objects.filter(scene_id=kwargs.scene_id, product_id=kwargs.product_id, flag=const.SceneFlag.SPECIFIC).count()
    scene_product_list = json.loads(cache.get(str(key)))
    if scene_product_list and len(cache.get(str(key))) >= pa:
        pa_induction = ProductAutomation.objects.filter(scene_id=kwargs.scene_id, product_id=kwargs.product_id,
                                                        flag=const.SceneFlag.INDUCTION).prefetch_related("product").all()
        for pa in pa_induction:
            pass
    else:
        if isinstance(scene_product_list, list):
            scene_product_list.append(kwargs.product_id)
        else:
            scene_product_list = [kwargs.product_id]
    cache.set(str(key), json.dumps(scene_product_list))
    cache.expire(str(key), 300)

    if scene and pa != 0:
        cls.product(kwargs.product_id, kwargs.user_id, kwargs.status)

@classmethod
def product(cls, product_id, user_id, status):
    product = Product.objects.filter(id=product_id)
    product_user = ProductUser.objects.filter(product_id=product_id, user_id=user_id)
    if product and product_user:
        Product.objects.filter(id=product_id).update(status=status)
        print("处理完成")
        return True
    return False

django连接mqtt 会连接两次

如果不设置client_id,会自动生成两个不通的id进行操作,如果设置了client id,感觉像是两个线程互相把对方挤掉线重连,如何避免这问题?

Web socket error: Connection closed before receiving a handshake response

When I run on 127.0.0.1:8000 your test example it works well. But when I am trying to connect to ThingSpeak it give me error:
WebSocket connection to 'ws://mqtt3.thingspeak.com:1883/' failed: Connection closed before receiving a handshake response

Here is ThingSpeaks documentation how to connect: https://www.mathworks.com/help/thingspeak/subscribetoachannelfeed.html
Here is my info:
connection: { host: 'mqtt3.thingspeak.com', port: 1883, endpoint: '/mqtt', clean: true, // Reserved session connectTimeout: 4000, // Time out reconnectPeriod: 4000, // Reconnection interval // Certification Information clientId: 'myId', username: 'myUsername', password: 'myPassword', },

Here is my Connect code:
createConnection() { // 连接字符串, 通过协议指定使用的连接方式 // ws 未加密 WebSocket 连接 // wss 加密 WebSocket 连接 // mqtt 未加密 TCP 连接 // mqtts 加密 TCP 连接 // wxs 微信小程序连接 // alis 支付宝小程序连接 const { host, port, endpoint, ...options } = this.connection const connectUrl =mqtt://${host}:${port}${endpoint} try { this.client = mqtt.connect(connectUrl, options) } catch (error) { console.log('mqtt.connect error', error) } this.client.on('connect', () => { console.log('Connection succeeded!') }) this.client.on('error', error => { console.log('Connection failed', error) }) this.client.on('message', (topic, message) => { this.receiveNews = this.receiveNews.concat(message) console.log(Received message ${message} from topic ${topic}) }) },

I tried changing in connectUrl mqtt and ws and mqtts and ws but does not work. I also tried removing endpointand addingtopicasendpoint` because there is no endpoint in ThingsSpeak documentation but still nothing.

Subscribe doesn't work

MQTT client's publish method has "retain" param. It is true or false.

I change the payload data at publish method.

If "retain" param is true value, subscribe method is getting the changed data every time.
But if "retain" param is false value, subscribe method is not getting the changed data.

How can I resolve this?

java的demo中的双向认证,客户端证书PKCS#8格式的密钥文件无法加载

openssl版本:OpenSSL 3.3.1 4 Jun 2024 (Library: OpenSSL 3.3.1 4 Jun 2024)
生成的证书密钥文件格式为:PKCS#8,示例中的只能加载PKCS#1的密钥。
请修改一下示例代码,能够适配两种,或者在生成证书时添加指定版本的参数。

报错信息:
org.bouncycastle.asn1.pkcs.PrivateKeyInfo cannot be cast to org.bouncycastle.openssl.PEMKeyPair

mqtt / nuxt 3 - Uncaught ReferenceError

As soon as I try to call the mqtt connect function, I get this error in the console:

Uncaught ReferenceError: Buffer is not defined
at node_modules/mqtt-packet/constants.js

Has anybody successfully gotten mqttjs to work in nuxt 3?

Process Not Defined(React Js)

Uncaught ReferenceError: process is not defined
at ./node_modules/mqtt/build/lib/client.js (client.ts:41:1)
at options.factory (react refresh:6:1)
at webpack_require (bootstrap:24:1)
at fn (hot module replacement:62:1)
at ./node_modules/mqtt/build/mqtt.js (mqtt.ts:8:1)
at options.factory (react refresh:6:1)
at webpack_require (bootstrap:24:1)
at fn (hot module replacement:62:1)
at ./src/components/MQTTConnector/index.js (index.js:15:1)
at options.factory (react refresh:6:1)

启动项目报错

使用vue2启动项目的时候,引入的是mqtt最新版本的包,但是启动报错了
error in ./node_modules/mqtt/lib/client.js

Module parse failed: Unexpected token (118:38)
You may need an appropriate loader to handle this file type.
| if (alias) {
| packet.topic = ''
| packet.properties = { ...(packet.properties), topicAlias: alias }
| debug('applyTopicAlias :: auto assign(use) topic: %s - alias: %d', topic, alias)
| } else {

React native example is full of error

got many error in This React Native Example

I copy app.js code in my react-native project,
but got many error like :
'client' is not defined.eslint
'idMessage' is not defined.
'newmessageList' is not defined.eslint

image

Is something I miss to install or any error in my code ?

Thank you

code:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow strict-local
 */

import React, {Component} from 'react';
import {View, Text, StyleSheet, FlatList} from 'react-native';

import {Input, Button} from '@rneui/base';
import AsyncStorage from '@react-native-async-storage/async-storage';
import init from 'react_native_mqtt';

init({
  size: 10000,
  storageBackend: AsyncStorage,
  defaultExpires: 1000 * 3600 * 24,
  enableCache: true,
  sync: {},
});
const options = {
  host: 'broker.emqx.io',
  port: 8083,
  path: '/testTopic',
  id: 'id_' + parseInt(Math.random() * 100000),
};
// 创建客户端实例
client = new Paho.MQTT.Client(options.host, options.port, options.path);

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      topic: 'testTopic',
      subscribedTopic: '',
      message: '',
      messageList: [],
      status: '',
    };
    client.onConnectionLost = this.onConnectionLost;
    client.onMessageArrived = this.onMessageArrived;
  }
  // 连接成功
  onConnect = () => {
    console.log('onConnect');
    this.setState({status: 'connected'});
  };
  // 连接失败
  onFailure = err => {
    console.log('Connect failed!');
    console.log(err);
    this.setState({status: 'failed'});
  };
  // 连接 MQTT 服务器
  connect = () => {
    this.setState({status: 'isFetching'}, () => {
      client.connect({
        onSuccess: this.onConnect,
        useSSL: false,
        timeout: 3,
        onFailure: this.onFailure,
      });
    });
  };
  // 连接丢失
  onConnectionLost = responseObject => {
    if (responseObject.errorCode !== 0) {
      console.log('onConnectionLost:' + responseObject.errorMessage);
    }
  };
  // 收到消息
  onMessageArrived = message => {
    console.log('onMessageArrived:' + message.payloadString);
    newmessageList = this.state.messageList;
    newmessageList.unshift(message.payloadString);
    this.setState({messageList: newmessageList});
    // this.MessageListRef.scrollToEnd({animated: false});
  };
  onChangeTopic = text => {
    this.setState({topic: text});
  };
  // 主题订阅
  subscribeTopic = () => {
    this.setState({subscribedTopic: this.state.topic}, () => {
      client.subscribe(this.state.subscribedTopic, {qos: 0});
    });
  };
  // 取消订阅
  unSubscribeTopic = () => {
    client.unsubscribe(this.state.subscribedTopic);
    this.setState({subscribedTopic: ''});
  };
  onChangeMessage = text => {
    this.setState({message: text});
  };
  // 消息发布
  sendMessage = () => {
    var message = new Paho.MQTT.Message(options.id + ':' + this.state.message);
    message.destinationName = this.state.subscribedTopic;
    client.send(message);
  };
  renderRow = ({item, index}) => {
    idMessage = item.split(':');
    console.log('>>>ITEM', item);
    return (
      <View
        style={[
          styles.componentMessage,
          idMessage[0] == options.id
            ? styles.myMessageComponent
            : idMessage.length == 1
            ? styles.introMessage
            : styles.messageComponent,
        ]}>
        <Text
          style={idMessage.length == 1 ? styles.textIntro : styles.textMessage}>
          {item}
        </Text>
      </View>
    );
  };
  _keyExtractor = (item, index) => item + index;
  render() {
    const {status, messageList} = this.state;
    return (
      <View style={styles.container}>
        <Text
          style={{
            marginBottom: 50,
            textAlign: 'center',
            color: this.state.status === 'connected' ? 'green' : 'black',
          }}>
          ClientID: {options.id}
        </Text>
        {this.state.status === 'connected' ? (
          <View>
            <Button
              type="solid"
              title="DISCONNECT"
              onPress={() => {
                client.disconnect();
                this.setState({status: '', subscribedTopic: ''});
              }}
              buttonStyle={{marginBottom: 50, backgroundColor: '#397af8'}}
              icon={{
                name: 'lan-disconnect',
                type: 'material-community',
                color: 'white',
              }}
            />
            <View style={{marginBottom: 30, alignItems: 'center'}}>
              <Input
                label="TOPIC"
                placeholder=""
                value={this.state.topic}
                onChangeText={this.onChangeTopic}
                disabled={this.state.subscribedTopic}
              />
              {this.state.subscribedTopic ? (
                <Button
                  type="solid"
                  title="UNSUBSCRIBE"
                  onPress={this.unSubscribeTopic}
                  buttonStyle={{backgroundColor: '#397af8'}}
                  icon={{
                    name: 'link-variant-off',
                    type: 'material-community',
                    color: 'white',
                  }}
                />
              ) : (
                <Button
                  type="solid"
                  title="SUBSCRIBE"
                  onPress={this.subscribeTopic}
                  buttonStyle={{backgroundColor: '#397af8'}}
                  icon={{
                    name: 'link-variant',
                    type: 'material-community',
                    color: 'white',
                  }}
                  disabled={
                    !this.state.topic || this.state.topic.match(/ /)
                      ? true
                      : false
                  }
                />
              )}
            </View>
            {this.state.subscribedTopic ? (
              <View style={{marginBottom: 30, alignItems: 'center'}}>
                <Input
                  label="MESSAGE"
                  placeholder=""
                  value={this.state.message}
                  onChangeText={this.onChangeMessage}
                />
                <Button
                  type="solid"
                  title="PUBLISH"
                  onPress={this.sendMessage}
                  buttonStyle={{
                    backgroundColor: status === 'failed' ? 'red' : '#397af8',
                  }}
                  icon={{name: 'send', color: 'white'}}
                  disabled={
                    !this.state.message || this.state.message.match(/^[ ]*$/)
                      ? true
                      : false
                  }
                />
              </View>
            ) : null}
          </View>
        ) : (
          <Button
            type="solid"
            title="CONNECT"
            onPress={this.connect}
            buttonStyle={{
              marginBottom: 50,
              backgroundColor: status === 'failed' ? 'red' : '#397af8',
            }}
            icon={{
              name: 'lan-connect',
              type: 'material-community',
              color: 'white',
            }}
            loading={status === 'isFetching' ? true : false}
            disabled={status === 'isFetching' ? true : false}
          />
        )}
        <View style={styles.messageBox}>
          <FlatList
            ref={ref => (this.MessageListRef = ref)}
            data={messageList}
            renderItem={this.renderRow}
            keyExtractor={this._keyExtractor}
            extraData={this.state}
          />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 70,
  },
  messageBox: {
    margin: 16,
    flex: 1,
  },
  myMessageComponent: {
    backgroundColor: '#000000',
    borderRadius: 3,
    padding: 5,
    marginBottom: 5,
  },
  messageComponent: {
    marginBottom: 5,
    backgroundColor: '#0075e2',
    padding: 5,
    borderRadius: 3,
  },
  introMessage: {},
  textInput: {
    height: 40,
    margin: 5,
    borderWidth: 1,
    padding: 5,
  },
  textIntro: {
    color: 'black',
    fontSize: 12,
  },
  textMessage: {
    color: 'white',
    fontSize: 16,
  },
});

export default App;

my package.js

  "dependencies": {
    "@react-native-async-storage/async-storage": "^1.17.9",
    "@rneui/base": "^4.0.0-rc.6",
    "@rneui/themed": "^4.0.0-rc.6",
    "react": "18.0.0",
    "react_native_mqtt": "^1.3.1",
    "react-native": "0.69.4"
  },

websocket timeout error

Hi, this is my first time using MQTT and I can loads of examples using TCP. But I'm trying to use websockets. I tried to connect to mqtt broker and subscribe to a topic via mqttbox and I can do it successfully. But when I try the same thing via code, I get timeout error. Details shown below:

Expected behavior: Successful connection to the mqtt broker, no errors
Actual behavior: "mqtt client encounter error connecting: network Error : dial tcp x.x.x.x:XXXX: i/o timeout"

Code snippet:

broker := fmt.Sprintf("ws://%s:%d/mqtt", "address", 1234)

//Create the broker
opts = mqtt.NewClientOptions()
opts.AddBroker(broker)
opts.SetClientID(fmt.Sprintf("clientID.%s", time.Now()))
opts.SetUsername(Username)
opts.SetPassword(Password)

mqttClient = mqtt.NewClient(opts)

if token := mqttClient.Connect(); token.Wait() && token.Error() != nil {
	fmt.Println(err)      // This is the error point I hit
}

I've tried the broker with wss and ws, no luck!
Any help/suggestions would be greatly appreciated. Thanks in advance!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.