aladin8848 aladin8848 - 1 month ago 19
C++ Question

Qt websocket send message and wait for response before going to next method

I am working with Qt websockets.

Wanted to ask you, do you know how could I make this communication:

for example I have this two methods and I would like to send message to server, than wait for response (because it refreshes the

data
variable) and than proccess
myMethod()


client->sendMessageToServer();
myMethod(data);


Sure I could use Signal and Slots... but dont know how could I use it here, see:

when I go
sendMessageToServer()
ok it will send message to server

void Client::sendMessageToServer(QString &str){

m_wSocket.sendTextMessage(str);
}


what should I emit than? I have no idea how to be in waiting state... there is no such a slot in
QWebSocket
, it just go to method
myMethod
immediately.
It doesn't go here where the data are set:
btw I have setup client like this when it recieves message it goes to
onTextMessageRecieved
because of this:

connect(&m_wSocket, &QWebSocket::textMessageReceived, this, &Client::onTextMessageReceived);

void Client::onTextMessageReceived(QString message)
{
setData(message);
}


Do you have any idea?

Answer

You can emit a signal on setData or onTextMessageReceived and connect to this.

void Client::setData(QString message)
{
    //... whatever you do in setData

    emit dataChanged();       
}

in the other class you then can do

connect(client, &Client::dataChanged,this,&<...>::myMethod);

then just call

client->sendMessageToServer();
//without the myMethod call

And whenever setData will be called myMethod will automatically be called too.

Qt is not meant to be "waiting" most of the times. It is event driven. You define an event (or use one already existing) and tell the program what to do when this event happens.

It is a bit unusual compared to "normal" programming but you get used to it.