I’m trying to write a program that reads broadcasted UDP datagrams in linux.I’m a beginner in socket programming .
My code is :
#include <QUdpSocket>
#include <iostream>
int main ()
{
QUdpSocket *udpSocket ;
udpSocket= new QUdpSocket(0);
udpSocket->bind(QHostAddress::LocalHost, 3838);
udpSocket->connect(udpSocket, SIGNAL(readyRead()),
this, SLOT(readPendingDatagrams()));
while (1)
{
if (udpSocket->hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(udpSocket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
udpSocket->readDatagram(datagram.data(), datagram.size(),
&sender, &senderPort);
}
}
}
but it returns error in this.
main.cpp:13:18: error: invalid use of ‘this’ in non-member function
what should I do ?
You need an event loop to use signals and slots (with a
QCoreApplication,QApplication, orQEventLoop) and aQObjectderived class to host the slots.But you can use the sockets synchronously without signal/slot or an event loop, by using the functions
QUdpSocket::waitForReadyRead,waitForBytesWritten… :Edit: To listen to broadcast UDP datagrams, you also should not listen to
QHostAddress::LocalHostbut toQHostAddress::Any(or at least to an IP address attached to an external interface).