How to write a C++ socket programming based UDP with QT?
You need an event loop to use signals and slots (with a QCoreApplication
, QApplication
, or QEventLoop
) and a QObject
derived 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
... :
#include <QUdpSocket>
#include <QTextStream>
int main()
{
QTextStream qout(stdout);
QUdpSocket *udpSocket = new QUdpSocket(0);
udpSocket->bind(3838, QUdpSocket::ShareAddress);
while (udpSocket->waitForReadyRead(-1)) {
while(udpSocket->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(udpSocket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
udpSocket->readDatagram(datagram.data(), datagram.size(),
&sender, &senderPort);
qout << "datagram received from " << sender.toString() << endl;
}
}
}
Edit: To listen to broadcast UDP datagrams, you also should not listen to QHostAddress::LocalHost
but to QHostAddress::Any
(or at least to an IP address attached to an external interface).
Hamed
Java Software Developer with 5+ years of progressive experience in IT industry, involved in complete Software Development Life Cycle including analysis, design, development, testing, implementation, support, and maintenance of enterprise-level applications. I have focused on RESTful large-scale, highly available microservice applications and modern application development methodologies like TDD using scrum. As a java developer, I'm always ready to learn new things, especially the challenging ones which I might face in my job.
Updated on June 04, 2022Comments
-
Hamed about 2 years
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 ?
-
alexisdm about 12 years@hamed: Yes, it worked for me. I tested the code on linux (with netcat as the sender).
-
alexisdm about 12 yearsBut since you added "broadcast" to your question, I edited my answer accordingly.