当前位置: 首页 > article >正文

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

<!--mqtt依赖-->
    <dependency>
      <groupId>org.eclipse.paho</groupId>
      <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
      <version>1.2.5</version>
    </dependency>

发布消息 PublishSample:

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:

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入门示例

// 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');
});



http://www.kler.cn/a/369511.html

相关文章:

  • 【Linux学习】(9)调试器gdb
  • outlook创建新账户时报错2603、2604的解决办法
  • 电机学习-SVPWM合成原理
  • Vue学习记录之二十五 Vue3中Web Componets的使用
  • SpringMVC6-SpringMVC的视图
  • 分库分表常见面试问题
  • RK3568 android11 usb接口TP与电磁笔触点上报优先级问题
  • HCIP-HarmonyOS Application Developer 习题(十八)
  • Unity URP ShaderGraph 基本设置
  • [论文阅读]Detecting Pretraining Data from Large Language Models
  • Windows服务器如何远程登录 #服务器远程教程#
  • 大数据-192 DataX - 异构数据源的同步工具 核心模块 Reader Writer
  • 【微服务】Nacos 注册中心
  • 实时面部情绪识别技术解析
  • 大券商和小券商开户,哪个更划算?
  • 算法:利用前序序列和中序序列构造二叉树
  • Spring常见面试题总结
  • java程序,生成mysql测试数据
  • 高并发-负载均衡
  • 《Python游戏编程入门》注-第4章1
  • DevOps --- Pipeline和Yaml文件
  • 有人问我:过去一年用 AI 写了多少代码
  • 力扣 —— 加油站
  • 开源实时数仓的构建
  • NYSQL期中小结
  • Redis 命令集 (超级详细)