#include #include #include #include #include #include // // trivial UDP socket class that sends datagrams to a server and // processes any replies that may turn up // class MyUdpSocket final : public QUdpSocket { Q_OBJECT public: MyUdpSocket (QObject* parent = nullptr) : QUdpSocket {parent} { // report socket errors connect (this, static_cast (&MyUdpSocket::error) , [this] (MyUdpSocket::SocketError const& err) { qDebug () << "socket error:" << err << ":" << errorString (); }); connect (this, &MyUdpSocket::readyRead, this, &MyUdpSocket::get_reply); // bind to ephemeral port for any replies from server if (!bind ()) qDebug () << "bind failed"; // send periodic datagrams to any server listening localhost:2237 auto timer = new QTimer {this}; connect (timer, &QTimer::timeout, [this]() { static const QByteArray ba {10, 'a'}; auto bytes_sent = writeDatagram(ba, QHostAddress::LocalHost, 2237); qDebug () << "wrote" << bytes_sent << "byte datagram"; }); timer->start (2000); } private: // process replies from server Q_SLOT void get_reply () { int i {0}; while (hasPendingDatagrams ()) { buffer_.resize (pendingDatagramSize ()); QHostAddress sender; quint16 sender_port; auto size = readDatagram (buffer_.data (), buffer_.size (), &sender, &sender_port); qDebug() << ++i << "read" << size << "of" << buffer_.size () << "bytesAvailable()" << bytesAvailable (); } } QByteArray buffer_; }; int main (int argc, char * argv[]) { QCoreApplication a {argc, argv}; MyUdpSocket socket; return a.exec (); } #include "main.moc"