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');
});
相关推荐
技术旅人17 分钟前
MQTT物联网消息队列的概念介绍以及broker选型对比
物联网·mqtt
得单片机的运12 小时前
STM32的以太网的搭建
stm32·单片机·嵌入式硬件·物联网·以太网·iot·w5500
文火冰糖的硅基工坊17 小时前
[嵌入式系统-108]:定昌电子DC-A588电路板介绍,一款基于瑞芯微RK3588芯片的高性能嵌入式AI边缘计算工控主机
人工智能·物联网·边缘计算
2401_8854055121 小时前
定位守护童年,科技构筑安全屏障
科技·物联网·安全·小程序·宠物·web app·智能手表
openHiTLS密码开源社区21 小时前
【密码学实战】openHiTLS s_server命令行:搭建国密标准安全通信服务器
服务器·物联网·密码学·openhitls·tlcp·商用密码算法·dtlcp
搞科研的小刘选手1 天前
【大会邀请】2025年AI驱动下:业务转型和数据科学创新国际学术会议(ICBTDS 2025)
人工智能·物联网·大模型·智慧城市·数据科学·ai驱动·计算科学
b***25111 天前
赋能高效电池制造:圆柱电芯组合式双面自动点焊技术
物联网·自动化
Net_Walke2 天前
【Linux系统】文件IO
linux·物联网·iot
riveting2 天前
48 元四核 ARM 核心板!明远智睿 2351 进入嵌入式市场
物联网·智能家居·嵌入式开发·明远智睿·2351核心板
wh_xia_jun2 天前
Python串口通信与MQTT物联网网关:连接STM32与物联网平台
python·stm32·物联网