redboltz/mqtt_cpp

How to add timeout to the client

Closed this issue · 6 comments

Hello, please advice how could I add a timeout if I am not able to connect to broker for couple of minutes for example.
The problem is that I am not receiving any errors, callbacks are not called for me. Thanks in advance

Do you use async API or sync API?

Thank you very much for your quick reply. I am using both for different projects.

If you use sync_connect(), there is no way to timeout because underlying Boost.Asio sync APIs doesn't provide timeout.
If you use async_connect(), you can use asio timer by yourself.
e.g. steady_timer.

If timer is fired then you can call async_force_disconnect() from your timer handler.
Be careful using timer. There is a trap. See https://stackoverflow.com/questions/43045192/how-to-avoid-firing-already-destroyed-boostasiodeadline-timer

See also #976 it could help understanding.

It's too said that we do not have timeout in sync connect. I think I will use async in all my projects.
P.S.: You are doing great job with this project. I am using it everywhere. Thanks

You are welcome.
Boost.Asio sync APIs are very easy to use and casual. However, if we do something seriously, we would have many issues. The core reason is sync APIs' blocking behavior.

I noticed this issue after I implement both sync and async APIs for mqtt_cpp. I thought that I want to maximize async APIs flexibility, however the sync part of mqtt_cpp implementation prevents it.
Finally, I decided to start the new project https://github.com/redboltz/async_mqtt , it doesn't have sync part, so there is no limitation. It has already implemented all functionality that is the same as mqtt_cpp except UTF8 validation.

I don't know your project situation, but migrating async_mqtt could be a choice. See the top page of mqtt_cpp project. It is now bugfix only status.