Qt5 Tutorial QUdpSocket - 2020
In this tutorial, we will learn QUdpSocket.
The most common way to use QUdpSocket class is to bind to an address and port using bind(), then call writeDatagram() and readDatagram() to transfer data. We'll do exactly that in this tutorial.
Note: Qt5 document
UDP (User Datagram Protocol) is a lightweight, unreliable, datagram-oriented, connectionless protocol.
It can be used when reliability isn't important. QUdpSocket is a subclass of QAbstractSocket that allows you to send and receive UDP datagrams.
For UDP Socket in general, please visit my C++ Tutorials: Socket - Server and Client.
We'll start with Qt Console Application.
First, we need to add network module to our project file, QUdpSocket.pro:
QT += core QT += network QT -= gui TARGET = QUdpSocket CONFIG += console CONFIG -= app_bundle TEMPLATE = app SOURCES += main.cpp
Then, we want to create a new class called MyUdpSocket.
The most common way to use QUdpSocket class is to bind to an address and port using bind(), then call writeDatagram() and readDatagram() to transfer data. We do exactly that in this tutorial.
- In main(), we create an instance of MyUDP class:
MyUDP client;
- In the constructor, MyUDP::MyUDP(), a QUdpSocket will be created:
socket = new QUdpSocket(this);
- Then, we bind it to an address and port:
socket->bind(QHostAddress::LocalHost, 1234);
- In main(), we call MyUDP::HelloUDP(), and it actually sends data gram:
socket->writeDatagram(Data, QHostAddress::LocalHost, 1234);
- When the data comes in, we read that datagram in MyUDP::readyRead():
socket->readDatagram(buffer.data(), buffer.size(), &sender;, &senderPort;);
Here are the files used in this tutorial.
main.cpp:
#include <QCoreApplication> #include "myudp.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); MyUDP client; client.HelloUDP(); return a.exec(); }
myudp.h:
// myudp.h #ifndef MYUDP_H #define MYUDP_H #include <QObject> #include <QUdpSocket> class MyUDP : public QObject { Q_OBJECT public: explicit MyUDP(QObject *parent = 0); void HelloUDP(); signals: public slots: void readyRead(); private: QUdpSocket *socket; }; #endif // MYUDP_H
myudp.cpp:
// myudp.cpp #include "myudp.h" MyUDP::MyUDP(QObject *parent) : QObject(parent) { // create a QUDP socket socket = new QUdpSocket(this); // The most common way to use QUdpSocket class is // to bind to an address and port using bind() // bool QAbstractSocket::bind(const QHostAddress & address, // quint16 port = 0, BindMode mode = DefaultForPlatform) socket->bind(QHostAddress::LocalHost, 1234); connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead())); } void MyUDP::HelloUDP() { QByteArray Data; Data.append("Hello from UDP"); // Sends the datagram datagram // to the host address and at port. // qint64 QUdpSocket::writeDatagram(const QByteArray & datagram, // const QHostAddress & host, quint16 port) socket->writeDatagram(Data, QHostAddress::LocalHost, 1234); } void MyUDP::readyRead() { // when data comes in QByteArray buffer; buffer.resize(socket->pendingDatagramSize()); QHostAddress sender; quint16 senderPort; // qint64 QUdpSocket::readDatagram(char * data, qint64 maxSize, // QHostAddress * address = 0, quint16 * port = 0) // Receives a datagram no larger than maxSize bytes and stores it in data. // The sender's host address and port is stored in *address and *port // (unless the pointers are 0). socket->readDatagram(buffer.data(), buffer.size(), &sender;, &senderPort;); qDebug() << "Message from: " << sender.toString(); qDebug() << "Message port: " << senderPort; qDebug() << "Message: " << buffer; }
Qt 5 Tutorial
- Hello World
- Signals and Slots
- Q_OBJECT Macro
- MainWindow and Action
- MainWindow and ImageViewer using Designer A
- MainWindow and ImageViewer using Designer B
- Layouts
- Layouts without Designer
- Grid Layouts
- Splitter
- QDir
- QFile (Basic)
- Resource Files (.qrc)
- QComboBox
- QListWidget
- QTreeWidget
- QAction and Icon Resources
- QStatusBar
- QMessageBox
- QTimer
- QList
- QListIterator
- QMutableListIterator
- QLinkedList
- QMap
- QHash
- QStringList
- QTextStream
- QMimeType and QMimeDatabase
- QFile (Serialization I)
- QFile (Serialization II - Class)
- Tool Tips in HTML Style and with Resource Images
- QPainter
- QBrush and QRect
- QPainterPath and QPolygon
- QPen and Cap Style
- QBrush and QGradient
- QPainter and Transformations
- QGraphicsView and QGraphicsScene
- Customizing Items by inheriting QGraphicsItem
- QGraphicsView Animation
- FFmpeg Converter using QProcess
- QProgress Dialog - Modal and Modeless
- QVariant and QMetaType
- QtXML - Writing to a file
- QtXML - QtXML DOM Reading
- QThreads - Introduction
- QThreads - Creating Threads
- Creating QThreads using QtConcurrent
- QThreads - Priority
- QThreads - QMutex
- QThreads - GuiThread
- QtConcurrent QProgressDialog with QFutureWatcher
- QSemaphores - Producer and Consumer
- QThreads - wait()
- MVC - ModelView with QListView and QStringListModel
- MVC - ModelView with QTreeView and QDirModel
- MVC - ModelView with QTreeView and QFileSystemModel
- MVC - ModelView with QTableView and QItemDelegate
- QHttp - Downloading Files
- QNetworkAccessManager and QNetworkRequest - Downloading Files
- Qt's Network Download Example - Reconstructed
- QNetworkAccessManager - Downloading Files with UI and QProgressDialog
- QUdpSocket
- QTcpSocket
- QTcpSocket with Signals and Slots
- QTcpServer - Client and Server
- QTcpServer - Loopback Dialog
- QTcpServer - Client and Server using MultiThreading
- QTcpServer - Client and Server using QThreadPool
- Asynchronous QTcpServer - Client and Server using QThreadPool
- Qt Quick2 QML Animation - A
- Qt Quick2 QML Animation - B
- Short note on Ubuntu Install
- OpenGL with QT5
- Qt5 Webkit : Web Browser with QtCreator using QWebView Part A
- Qt5 Webkit : Web Browser with QtCreator using QWebView Part B
- Video Player with HTML5 QWebView and FFmpeg Converter
- Qt5 Add-in and Visual Studio 2012
- Qt5.3 Installation on Ubuntu 14.04
- Qt5.5 Installation on Ubuntu 14.04
- Short note on deploying to Windows
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization