MQTT系列 | Retained消息和LWT和Keep Alive

本文详细介绍了MQTT协议中的Retained消息、LWT(Last Will and Testament)和Keep Alive机制。Retained消息允许Broker保存最新消息,新订阅者会立即收到;LWT用于在Client非正常断开连接时发布遗愿消息;Keep Alive机制确保连接状态的检测和保活。文中通过代码实践展示了这些特性的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. Retained消息

Retained 消息是指在 PUBLISH 数据包中 Retain 标识设为 1 的消息,Broker 收到这样的 PUBLISH 包以后,将保存这个消息,当有一个新的订阅者订阅相应主题的时候,Broker 会马上将这个消息发送给订阅者。有以下这些特点:

  • 一个Topic只能有一条Retained消息,发布新的Retained 消息将覆盖老的 Retained 消息(所以想删除一个 Retained 消息也很简单,只要向这个主题发布一个 Payload 长度为 0 的 Retained 消息就可以了);
  • 如果订阅者使用通配符订阅主题,它会收到所有匹配的主题上的 Retained 消息;
  • 只有新的订阅者才会收到 Retained 消息,如果订阅者重复订阅一个主题,也会被当做新的订阅者,然后收到 Retained 消息;
  • Broker 收到 Retained 消息后,会单独保存一份,再向当前的订阅者发送一份普通的消息(Retained 标识为 0)。当有新订阅者的时候, Broker 会把保存的这条消息发给新订阅者(Retained 标识为 1)。

Retained消息和持久性会话的区别:

Retained消息是Broker为每一个Topic单独存储的;

持久性会话是Broker为每一个Client单独存储的

1.1. 代码实践

下面是publisher的代码,在发送消息时指定retain为true

import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        client.publish("test", payload="hello world", qos=0, retain=True)
    else:
        print("connection failed ", rc)

mqtt_client = mqtt.Client(client_id="demo_mqtt_pub")
mqtt_client.on_connect = on_connect

mqtt_client.connect("192.168.10.239", 1883)
mqtt_client.loop_forever()

下面是subscriber的代码

import paho.mqtt.client as mqtt

'''
当代理响应订阅请求时被调用
'''
def on_subscribe(client, userdata,
### MQTT TTX Protocol Implementation and Configuration Details The MQTT (Message Queuing Telemetry Transport) protocol is designed to provide lightweight messaging services suitable for constrained devices with limited network bandwidth. The core features of the MQTT protocol include publish/subscribe message patterns, transport over TCP/IP or other network protocols that support ordered, lossless, bidirectional connections[^1]. For implementing and configuring an MQTT client using C++ specifically targeting embedded systems or cross-compilation environments, one can utilize libraries such as `paho.mqtt.cpp`. This library offers comprehensive APIs for connecting to brokers, publishing messages, subscribing topics, handling callbacks when receiving subscribed data, disconnecting from servers gracefully, etc.[^2]. When it comes to transmission specifics within MQTT: - **Quality of Service Levels**: There are three levels defined by QoS0 ("At most once"), where messages may be lost but will not be duplicated; QoS1 ("At least once") ensures delivery at least once without guarantee against duplicates; finally, QoS2 ("Exactly once") guarantees exactly-once-delivery semantics. - **Retained Messages**: Servers store a single last known good value per topic which new subscribers receive immediately upon subscription. - **Last Will Testament (LWT)**: Clients specify what should happen after unexpected disconnections occur so connected peers know about this event promptly. In terms of configuration aspects related to MQTT implementations: - Setting up security measures like username/password authentication mechanisms along with TLS encryption between clients & broker endpoints enhances overall system robustness while protecting sensitive information during transit. - Configuring keep-alive intervals helps maintain persistent sessions even under unstable networking conditions ensuring timely reconnection attempts whenever necessary. Below demonstrates how these concepts might look implemented via code snippets utilizing Paho's CPP API: ```cpp #include <mqtt/client.h> // ... void on_connect(bool sessionPresent){ std::cout << "Connected!" << std::endl; } int main(){ mqtt::client cli("tcp://localhost:1883", "example_client"); auto connOpts = mqtt::connect_options_builder() .clean_session(true) .finalize(); cli.set_callback(mqtt::callback(on_connect)); try { cli.connect(connOpts)->wait(); // Publish Message Example cli.publish("test/topic","Hello World!",false,QOS_1); // Subscribe Topic Example cli.subscribe("another/test_topic",QOS_1); // Disconnect Gracefully After Some Time std::this_thread::sleep_for(std::chrono::seconds(5)); cli.disconnect()->wait(); } catch(const mqtt::exception& exc) { std::cerr << "Error : " << exc.what() << std::endl; } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值