当前位置:网站首页>Mqtt disconnect and reconnect

Mqtt disconnect and reconnect

2022-06-26 11:16:00 Enlarged EZ

problem

Recent development projects require MQTT, When the development completes the test, it is often found that the connection is disconnected .

There is no error message , In the omnipotent Baidu search to see if there are any netizens who have encountered the same problem , It turns out that it may be the client ID The problem of , I start the same client every time ID, Previous clients ID stay MQTT The server is still stored and not cleaned up , If you start the client again, you will not be able to connect .

resolvent

Use random numbers to survive clients ID, Restart , Problem solved , Not always connected and disconnected .

The project has been running for several days and a new problem is found , If there is no operation for a long time, the connection will still be disconnected , Unable to send and receive messages .

Check it online MQTT Related articles , Learn more about MQTT, Find out MQTT There is an automatic reconnection function . There are two ways to achieve automatic reconnection .

1、MQTT Connection configuration class MqttConnectOption Class can set automatic reconnection . Here's the picture :

After setting automatic reconnection ,callback To achieve MqttCallbackExtended, There is a callback method for connection completion in this interface connectComplete(boolean reconnect,String serverURI), After the connection is completed, you can subscribe to the topic . Here's the picture :

 

2、 Custom reconnection

If MQTT Connection configuration class MqttConnectOption Class does not configure automatic reconnection , You can also do custom reconnection .MqttCallback There is a in the interface connectionLost(Throwable arg0) Interface , You can customize reconnection in the implementation method of this interface . Here's the picture :

summary

That's about MQTT Some problems of disconnection and reconnection , I hope I can help you .

Reprint of the article :

MQTT Disconnect and reconnect

原网站

版权声明
本文为[Enlarged EZ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206261019005500.html