QUdpSocket Class

QUdpSocket 提供了 UDP 类型的套接字. More...

头文件: #include <QUdpSocket>
qmake: QT += network
基类: QAbstractSocket

Note: All functions in this class are reentrant.

公有函数

QUdpSocket(QObject *parent = nullptr)
virtual ~QUdpSocket()
bool hasPendingDatagrams() const
bool joinMulticastGroup(const QHostAddress &groupAddress)
bool joinMulticastGroup(const QHostAddress &groupAddress, const QNetworkInterface &iface)
bool leaveMulticastGroup(const QHostAddress &groupAddress)
bool leaveMulticastGroup(const QHostAddress &groupAddress, const QNetworkInterface &iface)
QNetworkInterface multicastInterface() const
qint64 pendingDatagramSize() const
qint64 readDatagram(char *data, qint64 maxSize, QHostAddress *address = nullptr, quint16 *port = nullptr)
QNetworkDatagram receiveDatagram(qint64 maxSize = -1)
void setMulticastInterface(const QNetworkInterface &iface)
qint64 writeDatagram(const char *data, qint64 size, const QHostAddress &address, quint16 port)
qint64 writeDatagram(const QNetworkDatagram &datagram)
qint64 writeDatagram(const QByteArray &datagram, const QHostAddress &host, quint16 port)

其他继承的成员

详细描述

UDP (User Datagram Protocol) 是一种轻量级, 不可靠, 面向数据报的无连接协议. 当在数据传输的可靠性不重要时你可以选择使用它. QUdpSocket 是 QAbstractSocket 的子类, 可以发送和接收 UDP 数据报.

最常见的使用方法是使用 bind() 绑定地址和端口, 然后调用 writeDatagram() 和 readDatagram() / receiveDatagram() 传输数据. 如果你使用标准 QIODevice 的函数 read(), readLine(), write()等, 你必须先调用 connectToHost() 将套接字连接到对等方.

每次将数据报写入网络后, 套接字都会发出 bytesWritten() 信号. 如果你只想发送数据报, 则不需要调用 bind().

每次有数据报到达时, 套接字都会发出 readyRead() 信号. 在新数据到达时, hasPendingDatagrams() 返回 true. 调用 pendingDatagramSize() 获取第一个待处理的数据报大小, 然后调用readDatagram() 或 receiveDatagram() 读取数据.

注意: 当你收到 readyRead() 信号时, 必须将到达的数据报读入, 否则在接下来新的数据报到达后不会将发送 readyRead() 信号.

例如:

 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 还支持 UDP 多播功能. 你可以使用 joinMulticastGroup() 和 leaveMulticastGroup() 函数控制组成员身份, 并使用 QAbstractSocket::MulticastTtlOptionQAbstractSocket::MulticastLoopbackOption 设置 TTL 和回送套接字选项. 你也可以使用 setMulticastInterface() 函数控制多播数据报的传出接口, 并使用 multicastInterface() 函数查询传出接口.

使用 QUdpSocket 时, 你可以使用 connectToHost() 函数建立一个虚拟连接到 UDP 服务器. 虚拟连接建立后, 你可以用 read() 和 write() 函数交换数据报而不用指定每个数据报的接收者.

官方示例: Broadcast Sender, Broadcast Receiver, Multicast Sender, Multicast Receiver 演示如何在应用程序中使用 QUdpSocket.

另见 QTcpSocket, QNetworkDatagram.

Member Function Documentation

QUdpSocket::QUdpSocket(QObject *parent = nullptr)

Creates a QUdpSocket object.

parent is passed to the QObject constructor.

See also socketType().

[virtual] QUdpSocket::~QUdpSocket()

Destroys the socket, closing the connection if necessary.

See also close().

bool QUdpSocket::hasPendingDatagrams() const

Returns true if at least one datagram is waiting to be read; otherwise returns false.

See also pendingDatagramSize() and readDatagram().

bool QUdpSocket::joinMulticastGroup(const QHostAddress &groupAddress)

Joins the multicast group specified by groupAddress on the default interface chosen by the operating system. The socket must be in BoundState, otherwise an error occurs.

Note that if you are attempting to join an IPv4 group, your socket must not be bound using IPv6 (or in dual mode, using QHostAddress::Any). You must use QHostAddress::AnyIPv4 instead.

This function returns true if successful; otherwise it returns false and sets the socket error accordingly.

Note: Joining IPv6 multicast groups without an interface selection is not supported in all operating systems. Consider using the overload where the interface is specified.

This function was introduced in Qt 4.8.

See also leaveMulticastGroup().

bool QUdpSocket::joinMulticastGroup(const QHostAddress &groupAddress, const QNetworkInterface &iface)

This is an overloaded function.

Joins the multicast group address groupAddress on the interface iface.

This function was introduced in Qt 4.8.

See also leaveMulticastGroup().

bool QUdpSocket::leaveMulticastGroup(const QHostAddress &groupAddress)

Leaves the multicast group specified by groupAddress on the default interface chosen by the operating system. The socket must be in BoundState, otherwise an error occurs.

This function returns true if successful; otherwise it returns false and sets the socket error accordingly.

Note: This function should be called with the same arguments as were passed to joinMulticastGroup().

This function was introduced in Qt 4.8.

See also joinMulticastGroup().

bool QUdpSocket::leaveMulticastGroup(const QHostAddress &groupAddress, const QNetworkInterface &iface)

This is an overloaded function.

Leaves the multicast group specified by groupAddress on the interface iface.

Note: This function should be called with the same arguments as were passed to joinMulticastGroup().

This function was introduced in Qt 4.8.

See also joinMulticastGroup().

QNetworkInterface QUdpSocket::multicastInterface() const

Returns the interface for the outgoing interface for multicast datagrams. This corresponds to the IP_MULTICAST_IF socket option for IPv4 sockets and the IPV6_MULTICAST_IF socket option for IPv6 sockets. If no interface has been previously set, this function returns an invalid QNetworkInterface. The socket must be in BoundState, otherwise an invalid QNetworkInterface is returned.

This function was introduced in Qt 4.8.

See also setMulticastInterface().

qint64 QUdpSocket::pendingDatagramSize() const

Returns the size of the first pending UDP datagram. If there is no datagram available, this function returns -1.

See also hasPendingDatagrams() and readDatagram().

qint64 QUdpSocket::readDatagram(char *data, qint64 maxSize, QHostAddress *address = nullptr, quint16 *port = nullptr)

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 nullptr).

Returns the size of the datagram on success; otherwise returns -1.

If maxSize is too small, the rest of the datagram will be lost. To avoid loss of data, call pendingDatagramSize() to determine the size of the pending datagram before attempting to read it. If maxSize is 0, the datagram will be discarded.

See also writeDatagram(), hasPendingDatagrams(), and pendingDatagramSize().

QNetworkDatagram QUdpSocket::receiveDatagram(qint64 maxSize = -1)

Receives a datagram no larger than maxSize bytes and returns it in the QNetworkDatagram object, along with the sender's host address and port. If possible, this function will also try to determine the datagram's destination address, port, and the number of hop counts at reception time.

On failure, returns a QNetworkDatagram that reports not valid.

If maxSize is too small, the rest of the datagram will be lost. If maxSize is 0, the datagram will be discarded. If maxSize is -1 (the default), this function will attempt to read the entire datagram.

This function was introduced in Qt 5.8.

See also writeDatagram(), hasPendingDatagrams(), and pendingDatagramSize().

void QUdpSocket::setMulticastInterface(const QNetworkInterface &iface)

Sets the outgoing interface for multicast datagrams to the interface iface. This corresponds to the IP_MULTICAST_IF socket option for IPv4 sockets and the IPV6_MULTICAST_IF socket option for IPv6 sockets. The socket must be in BoundState, otherwise this function does nothing.

This function was introduced in Qt 4.8.

See also multicastInterface(), joinMulticastGroup(), and leaveMulticastGroup().

qint64 QUdpSocket::writeDatagram(const char *data, qint64 size, const QHostAddress &address, quint16 port)

Sends the datagram at data of size size to the host address address at port port. Returns the number of bytes sent on success; otherwise returns -1.

Datagrams are always written as one block. The maximum size of a datagram is highly platform-dependent, but can be as low as 8192 bytes. If the datagram is too large, this function will return -1 and error() will return DatagramTooLargeError.

Sending datagrams larger than 512 bytes is in general disadvised, as even if they are sent successfully, they are likely to be fragmented by the IP layer before arriving at their final destination.

Warning: Calling this function on a connected UDP socket may result in an error and no packet being sent. If you are using a connected socket, use write() to send datagrams.

See also readDatagram() and write().

qint64 QUdpSocket::writeDatagram(const QNetworkDatagram &datagram)

This is an overloaded function.

Sends the datagram datagram to the host address and port numbers contained in datagram, using the network interface and hop count limits also set there. If the destination address and port numbers are unset, this function will send to the address that was passed to connectToHost().

If the destination address is IPv6 with a non-empty scope id but differs from the interface index in datagram, it is undefined which interface the operating system will choose to send on.

The function returns the number of bytes sent if it succeeded or -1 if it encountered an error.

Warning: Calling this function on a connected UDP socket may result in an error and no packet being sent. If you are using a connected socket, use write() to send datagrams.

This function was introduced in Qt 5.8.

See also QNetworkDatagram::setDestination(), QNetworkDatagram::setHopLimit(), and QNetworkDatagram::setInterfaceIndex().

qint64 QUdpSocket::writeDatagram(const QByteArray &datagram, const QHostAddress &host, quint16 port)

This is an overloaded function.

Sends the datagram datagram to the host address host and at port port.

The function returns the number of bytes sent if it succeeded or -1 if it encountered an error.