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');
});
相关推荐
程序员JerrySUN1 小时前
嵌入式浏览器 -- Chromium VS Firefox
linux·前端·chrome·物联网·firefox·chrome devtools
沧穹科技15 小时前
沧穹科技室内音频“北斗”定位技术亮相第三届北斗规模应用国际峰会
人工智能·物联网
唯创知音16 小时前
语音提示器-WT3000A离在线TTS方案-打破语种限制/AI对话多功能支持
人工智能·单片机·物联网·智能家居·语音识别
白总Server18 小时前
论多端数据互通网游的架构评估
服务器·数据库·物联网·web安全·架构·php·idc
沐欣工作室_lvyiyi18 小时前
基于STM32的智能寝室控制系统设计(论文+源码)
stm32·单片机·嵌入式硬件·物联网·毕业设计·智能家居
limingade18 小时前
手机实时提取SIM卡打电话的信令声音-新的篇章(三、Android虚拟声卡探索)
android·linux·嵌入式硬件·物联网·智能手机
明达技术19 小时前
明达技术分布式IO在环保新材行业的应用
运维·物联网·自动化
RFID铨顺宏21 小时前
实时监控与数据安全:RFID在档案管理中的双重保护
大数据·网络·物联网·安全
图导物联1 天前
智慧停车场导航系统架构及反向寻车系统解决方案
java·linux·python·物联网·信息可视化·智慧城市