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;

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

connectionHandle = connect(pSocket, &QWebSocket::textMessageReceived,
			   [&eventLoop, &data](const QString message)
				   data = message;
pSocket->sendTextMessage("command to send");

// no message
// 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.


Post a Comment

Popular posts from this blog

Android: adb push and read-only file system error

Access GPIO from Linux user space

Launch an app from Android shell terminal