Mqtt协议快速入门Demo

Mqtt协议指南

入门

教程可以参考: https://www.emqx.com/zh/mqtt-guide

MQTT协议

可以参考:https://mcxiaoke.gitbooks.io/mqtt-cn/content/mqtt/02-ControlPacketFormat.html

消息队列遥测传输协议MQTT.

和HTTP协议不一样,MQTT采用的是二进制数据包。

由3各部分组成:

  • 固定头
  • 可变头
  • 消息体

一个入门的java示例demo

xml 复制代码
<!--mqtt依赖-->
    <dependency>
      <groupId>org.eclipse.paho</groupId>
      <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
      <version>1.2.5</version>
    </dependency>

发布消息 PublishSample:

java 复制代码
public class PublishSample {
  public static void main(String[] args) throws MqttException {
    String broker = "tcp://broker.emqx.io:1883";
    String topic = "mqtt/test";
    String username = "emqx";
    String password = "public";
    String clientid = "publish_client";
    String content = "Hello MQTT";
    int qos = 0;

    try {
      MqttClient client = new MqttClient(broker, clientid, new MemoryPersistence());
      // 连接参数
      MqttConnectOptions options = new MqttConnectOptions();
      // 设置用户名和密码
      options.setUserName(username);
      options.setPassword(password.toCharArray());
      options.setConnectionTimeout(60);
      options.setKeepAliveInterval(60);
      // 连接
      client.connect(options);
      // 创建消息并设置 QoS
      MqttMessage message = new MqttMessage(content.getBytes());
      message.setQos(qos);
      // 发布消息
      client.publish(topic, message);
      System.out.println("Message published");
      System.out.println("topic: " + topic);
      System.out.println("message content: " + content);
      // 关闭连接
      client.disconnect();
      // 关闭客户端
      client.close();
    } catch (MqttException e) {
      throw new RuntimeException(e);
    }
  }
}

消费消息 SubscribeSample:

java 复制代码
public class SubscribeSample {
  public static void main(String[] args) {
    String broker = "tcp://broker.emqx.io:1883";
    String topic = "mqtt/test";
    String username = "emqx";
    String password = "public";
    String clientid = "subscribe_client";
    int qos = 0;

    try {
      MqttClient client = new MqttClient(broker, clientid, new MemoryPersistence());
      // 连接参数
      MqttConnectOptions options = new MqttConnectOptions();
      options.setUserName(username);
      options.setPassword(password.toCharArray());
      options.setConnectionTimeout(60);
      options.setKeepAliveInterval(60);
      // 设置回调
      client.setCallback(new MqttCallback() {

        public void connectionLost(Throwable cause) {
          System.out.println("connectionLost: " + cause.getMessage());
        }

        public void messageArrived(String topic, MqttMessage message) {
          System.out.println("topic: " + topic);
          System.out.println("Qos: " + message.getQos());
          System.out.println("message content: " + new String(message.getPayload()));

        }

        public void deliveryComplete(IMqttDeliveryToken token) {
          System.out.println("deliveryComplete---------" + token.isComplete());
        }

      });
      client.connect(options);
      client.subscribe(topic, qos);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

一个nodejs入门示例

javascript 复制代码
// This code demonstrates how to use persistent connection in MQTT.
var mqtt = require('mqtt');


// create a client with persistent connection
var client = mqtt.connect('mqtt://mqtt.eclipse.org', {
    clean: false,  // set clean to false to use persistent connection
    clientId: 'persistent_client', // set client id to identify the persistent connection
    reconnectPeriod: 3000, // set reconnect period to 1000ms
});

client.on('connect', function (connect) {
    console.log('Connected to MQTT Broker. return code:${connect.returnCode}', sessionPresent:${connect.sessionPresent});
    client.subscribe('topic/test');
});
相关推荐
清风6666665 小时前
基于STM32单片机的OneNet物联网粉尘烟雾检测系统
stm32·单片机·物联网·毕业设计·课程设计
TDengine (老段)7 小时前
TDengine 特殊函数 MODE() 用户手册
大数据·数据库·物联网·时序数据库·iot·tdengine·涛思数据
余衫马8 小时前
开发指南:使用 MQTTNet 库构建 .Net 物联网 MQTT 应用程序
物联网·mqtt·.net
御控工业物联网1 天前
城市二次供水物联网监测管控管理平台御控解决方案:构建全链路智能水务新生态
物联网·数据采集·远程监控·物联网网关·二次供水·智能水务·泵站
电子科技圈1 天前
芯科科技FG23L无线SoC现已全面供货,为Sub-GHz物联网应用提供最佳性价比
科技·嵌入式硬件·mcu·物联网·制造·智能硬件·交通物流
禁默1 天前
第六届大数据、人工智能与物联网工程国际会议(ICBAIE 2025)
大数据·人工智能·物联网
糖糖单片机设计1 天前
硬件开发_基于物联网的沼气池环境监测系统
stm32·单片机·嵌入式硬件·物联网·51单片机
物联网平台1 天前
ThingsKit物联网平台 v2.0.0 发布|前端UI重构、底层架构升级
物联网·iot
The️1 天前
STM32-FreeRTOS操作系统-二值信号量与计数信号量
arm开发·stm32·单片机·嵌入式硬件·物联网
BYSJMG1 天前
计算机毕设推荐:基于Hadoop+Spark物联网网络安全数据分析系统 物联网威胁分析系统【源码+文档+调试】
大数据·hadoop·python·物联网·spark·django·课程设计