QWebSocket synchronous communication

QWebSocket can send or receive packet with text or binary contents. As all other Qt components everything works asynchronously. However, there may be cases where it is necessary to work asynchronously waiting for the reply to a given message before moving on. Here an example for a synchronous communication that you can use in your project.



The code use lambda function for receive the message reply and a timer for exit in case of no reply. The example is very short for highlight only the fundamental parts. Starting from this example you can adapt it in your project.
QMetaObject::Connection connectionHandle;
QEventLoop eventLoop;
QTimer timer;
QString data;

timer.setSingleShot(true);
connect(&timer, &QTimer::timeout, &eventLoop, &QEventLoop::quit);

connectionHandle = connect(pSocket, &QWebSocket::textMessageReceived,
			   [&eventLoop, &data](const QString message)
			   {
				   data = message;
				   eventLoop.quit();
			   });
timer.start(timeout);
pSocket->sendTextMessage("command to send");
eventLoop.exec();
timer.stop();
disconnect(connectionHandle);

if(data.isEmpty())
// no message
else
// message received
Please note in this example we try to know if the message received a reply by just check if the data string is empty or not. This is only a way to make this check, you have to find the best solution for your need.

Comments

Popular posts from this blog

Access GPIO from Linux user space

Android: adb push and read-only file system error

Tree in SQL database: The Nested Set Model