QUdpSocket Class
The QUdpSocket class provides a UDP socket. More...
| Header: | #include <QUdpSocket> |
| qmake: | QT += network |
| Inherits: | QAbstractSocket |
Note: All functions in this class are reentrant.
Detailed Description
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.
The most common way to use this class is to bind to an address and port using bind(), then call writeDatagram() and readDatagram() / receiveDatagram() to transfer data. If you want to use the standard QIODevice functions read(), readLine(), write(), etc., you must first connect the socket directly to a peer by calling connectToHost().
The socket emits the bytesWritten() signal every time a datagram is written to the network. If you just want to send datagrams, you don't need to call bind().
The readyRead() signal is emitted whenever datagrams arrive. In that case, hasPendingDatagrams() returns true. Call pendingDatagramSize() to obtain the size of the first pending datagram, and readDatagram() or receiveDatagram() to read it.
Note: An incoming datagram should be read when you receive the readyRead() signal, otherwise this signal will not be emitted for the next datagram.
Example:
void Server::initSocket() { udpSocket = new QUdpSocket(this); udpSocket->bind(QHostAddress::LocalHost, 7755); connect(udpSocket, &QUdpSocket::readyRead, this, &Server::readPendingDatagrams); } void Server::readPendingDatagrams() { while (udpSocket->hasPendingDatagrams()) { QNetworkDatagram datagram = udpSocket->receiveDatagram(); processTheDatagram(datagram); } }
QUdpSocket also supports UDP multicast. Use joinMulticastGroup() and leaveMulticastGroup() to control group membership, and QAbstractSocket::MulticastTtlOption and QAbstractSocket::MulticastLoopbackOption to set the TTL and loopback socket options. Use setMulticastInterface() to control the outgoing interface for multicast datagrams, and multicastInterface() to query it.
With QUdpSocket, you can also establish a virtual connection to a UDP server using connectToHost() and then use read() and write() to exchange datagrams without specifying the receiver for each datagram.
The Broadcast Sender, Broadcast Receiver, Multicast Sender, and Multicast Receiver examples illustrate how to use QUdpSocket in applications.
See also QTcpSocket and QNetworkDatagram.