QMQTT Client stuck connecting.
-
I'm trying to connect to a mosquito server running on my machine (default config, anonymous connections allowed). I can see the client connect but its state never progresses to connected and simply times out. Full code below.
#include <QCoreApplication> #include <QThread> #include <QtMqtt> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); const QString hostname{"127.0.0.1"}; const quint16 port = 1883; const QMqttTopicName topic{"Test"}; const QMqttTopicFilter filter{"Test"}; QMqttClient client; client.setHostname(hostname); client.setPort(port); QObject::connect(&client, &QMqttClient::stateChanged, [](QMqttClient::ClientState state){ if(state == QMqttClient::Disconnected) qDebug() << " State: Disconnected"; else if(state == QMqttClient::Connecting) qDebug() << " State: Connecting"; else if(state == QMqttClient::Connected) qDebug() << " State: Connected"; }); QObject::connect(&client, &QMqttClient::errorChanged, [](QMqttClient::ClientError error){ qDebug() << error; }); QObject::connect(&client, &QMqttClient::messageReceived, [](const QByteArray &message, const QMqttTopicName &topic){ qDebug() << " Received Topic:" << topic.name() << " Message: " << message; }); QTimer timer; QObject::connect(&timer, &QTimer::timeout, [&client, &topic](){ if(client.publish(topic, QDateTime::currentDateTime().toString().toUtf8()) == -1) qDebug() << "Error: Could not publish message"; }); QObject::connect(&client, &QMqttClient::connected, [&client, &timer, &filter](){ QMqttSubscription *subscription = client.subscribe(filter); if(!subscription) qDebug() << "Could not subscribe"; timer.start(1000); }); client.connectToHost(); while(1) { QThread::sleep(3); if(client.state() == QMqttClient::Connecting) { qDebug() << "Connecting"; } if(client.state() == QMqttClient::Connected) { qDebug() << "Connected"; } if(client.state() == QMqttClient::Disconnected) { qDebug() << "Disconnect"; } } return a.exec(); }
-
Hi and welcome to devnet,
@RFinchMinicam said in QMQTT Client stuck connecting.:
while(1)
You are blocking your application with that endless loop.
Qt is an asynchronous framework but you do not allow it to start the event loop. Therefore it cannot work properly. Drop that loop.
-
That works. So is QThread::sleep blocking? I've not used QT before and typically putting a thread to sleep will unblock for other events.
-
Your infinite loop never ends, so
a.exec();
will never be called therefore there's no events to start with.As for QThread::msleep, it makes the current thread sleep that's all. If it happens in the main thread the event loop will be blocked.
-
@RFinchMinicam said in QMQTT Client stuck connecting.:
I've not used QT before
You may want to take a look and try this client example.
You'll see there are no infinite loops but the usage of Qt's signals & slots instead.