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');
});
相关推荐
2601_9539880733 分钟前
Ricon组态系统vs传统组态软件:为什么选择新一代Web组态平台
前端·后端·物联网·tcp/ip·数学建模·前端框架
TDengine (老段)2 小时前
TDengine 第三方工具 — Telegraf、Kafka Connect、Flink、Spark
大数据·数据库·物联网·flink·kafka·时序数据库·tdengine
LCG元12 小时前
STM32+ESP8266+MQTT 物联网气象站:从零搭建温湿度远程监测系统(附完整源码)
stm32·物联网·struts
殷忆枫15 小时前
基于K210与STM32的智能垃圾分类与物联网监管系统
stm32·物联网·分类
老孙讲技术20 小时前
【4G IPC 上云】临时点位怎么免布线上云?listDeviceDetailsByPage + 辅码流预览|智慧工地实战
后端·物联网
数字新视界1 天前
信创动环监控厂家深入剖析智能机房环境监控技术应用与挑战
服务器·数据库·物联网·芯片·动环监控系统
笨鸟先飞,勤能补拙1 天前
AI Agent应用领域深度解析:从概念到落地的全维度审视
大数据·人工智能·python·物联网·安全·网络安全·github
星恒讯工业路由器2 天前
当无人机成为“空中路由器”:应急通信背后的联网技术支撑
物联网·信息与通信·wifi模块·无人机模块·无人机应急通信·空中基站·三断通信
会周易的程序员2 天前
aiDgePLC — IEC61131-3 ST PLC 虚拟机调试与运行环境
c++·物联网·虚拟机·st·工业协议·iec61131·梯形图
老孙讲技术2 天前
周末档期厨房爆单,带宽账单也爆了——不是直播难,是主码流 + always 计划在烧钱
后端·物联网