If the client does not send a messages during the keep-alive period, it must send a PINGREQ packet to the broker to confirm that it is available and to make sure that the broker is also still available.

如果客户端在保持活动期间未发送消息,则必须向代理发送PINGREQ包,以确认它是否可用,并确保代理仍然可用。

The broker must disconnect a client that does not send a message or a PINGREQ packet in one and a half times the keep alive interval. Likewise, the client is expected to close the connection if it does not receive a response from the broker in a reasonable amount of time.

代理必须断开客户端,该客户端在保持活动间隔的1.5T 内不发送消息或PINGREQ包。同样,如果客户机在合理的时间内没有收到代理的响应,则预期它将关闭连接。

说明:自己开发的体会,MQTT是基于TCP实现的,TCP里面的连接关闭,需要等待1.5个TLS,所以在开发MQTT时设置的是1.5TLS时间间隔,1.5TLS没有收到PINGREQ,认为连接断开,可以终止MQTT连接。

Keep Alive Flow

Let’s take a closer look at the keep alive messages. The keep alive feature uses two packets:

PINGREQ

springBoot整合mqtt心跳检测_发送消息

springBoot整合mqtt心跳检测_TCP_02

固定报头: 报头控制类型(0xc0),报文PINGREQ没有可变报头。

有效载荷: 剩余长度等于0, 报文PINGREQ没有有效载荷。

响应:  server收到PINGREQ报文时,必须使用PINGRESP报文响应。

The PINGREQ is sent by the client and indicates to the broker that the client is still alive. If the client does not send any other type of packets (for example, a PUBLISH or SUBSCRIBE packet), the client must send a PINGREQ packet to the broker. The client can send a PINGREQ packet any time it wants to confirm that the network connection is still alive. The PINGREQ packet does not contain a payload.

PINGREQ由客户端发送,并向代理指示客户端仍然有效。如果客户机不发送任何其他类型的数据包(例如,发布或订阅数据包),则客户机必须向代理发送PINGREQ数据包。客户机可以在任何时候发送一个PINGREQ数据包来确认网络连接仍然有效。PINGREQ数据包不包含有效负载。

 

PINGRESP

springBoot整合mqtt心跳检测_客户端_03

server发送给client的PINGRESP,用于确认它还活着。保持连接(Keep Alive)处理中用到这个报文。

固定报头: 报文PINGRESP没有可变报头。

有效载荷: 报文PINGRESP没有有效载荷。

springBoot整合mqtt心跳检测_mqtt_04

When the broker receives a PINGREQ packet, the broker must reply with a PINGRESP packet to show the client that it is still available. The PINGRESP packet also does not contain a payload.

当代理收到PINGREQ包时,代理必须用PINGRESP包进行应答,以向客户机显示它仍然可用。PINGRESP包也不包含有效负载。

Good to Know

  • If the broker does not receive a PINGREQ or any other packet from a client, the broker closes the connection and sends the last will and testament message (if the client specified an LWT).   如果代理没有从客户端接收到PINGREQ或任何其他数据包,那么代理将关闭连接并发送最后一条will和testament消息(如果客户端指定了LWT)。
  • It is the responsibility of the MQTT client to set an appropriate keep alive value. For example, the client can adjust the keep-alive interval to its current signal strength.     MQTT客户机负责设置适当的keep-alive值。例如,客户机可以将keep alive间隔调整为其当前信号强度。
  • The maximum keep alive is 18h 12min 15 sec.      最大存活时间为18小时12分15秒。
  • If the keep alive interval is 0, the keep alive mechanism is deactivated.      如果保持活动间隔为0,则停用保持活动机制。