I'm implementing a simple UDP server-client app. The main logic is: server starts sending broadcast -> clients responses -> server stops sending broadcast and performs some work.
I'm stuck with broadcasting loop:
sUDP::sUDP(QObject *parent) : QObject(parent)
{
serverSocket = new QUdpSocket(this);
serverIp = new QHostAddress("192.168.1.2");
pickUpThePhone = false;
if(serverSocket->state() != serverSocket->BoundState){
if (!serverSocket->bind(*serverIp, 4321)) {
qFatal("Error binding server");
}
}
connect(serverSocket,SIGNAL(readyRead()), SLOT(readSocket()));
while(!pickUpThePhone){
QByteArray Data;
Data.append("server");
serverSocket->writeDatagram(Data, Data.size(), QHostAddress("192.168.255.255"), 1234);
}
}
actually signal readyRead()
never emitted and so broadcasting never stops:
void sUDP::readSocket()
{
qDebug() << "read";
while(serverSocket->hasPendingDatagrams()){
QByteArray buffer;
buffer.resize(serverSocket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
serverSocket->readDatagram(buffer.data(), buffer.size(), &sender, &senderPort);
if(strcmp(buffer.data(),"stop") == 0){
pickUpThePhone = true;
}
}
}
The client works as it should - it responses to the datagram with "server" with "stop" message, but it looks like the while-loop is never interrupted. Any help will be useful, thank you.
It doesn't work because your program is busy sending broadcasts. Your while
loop will not let the Qt event-loop perform its work and therefore your program can't do anything else.
You're also sending broadcasts constantly, your computer will do nothing else than spam the network.
The solution to both problems is a timer. Create a repeating timer that once every second (ore more or less) sends out the broadcast. Stop or pause the timer when you get a response.