<QT>:使用QUdpSocket进行UDP通信

一、QUdpSocket类用法介绍

(以下内容为QT帮助文档中的原文)

The QUdpSocket class provides a UDP socket.

QUdpSocket类提供了一个UDP socket套接字

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.

UDP(用户数据报协议),是一个轻量的,不可靠的,面向数据报的,非连接的协议。当通讯要求的可靠性不重要时(可能数据会丢失),可以用UDP通信。QUdpSocket是QAbstractSocket的一个子类,它允许你发送和接收UDP数据报。

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

最常见的使用方式是用这个类中的函数 bind(),去绑定一个地址和端口,然后调用 writeDatagram() 和 readDatagram() / receiveDatagram() 去传输数据,如果你想用标准的 QIODevice 函数 read(), readLine(), write(),等,你必须先调用 connectToHost() 去连接socket到另一端。

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

扫描二维码关注公众号,回复: 6558614 查看本文章

当一个数据报被写进了网络中,socket就会发射一个bytesWritten()信号。如果你只是想发数据,不接收数据,那你就没必要调用 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.

无论什么时候,当有数据报到达,就会有一个叫 readyRead() 的信号被发出。在这种情况下,hasPendingDatagrams() 会返回一个true。调用 pendingDatagramSize() 去获取第一条在接收队列中等待取出的数据报的字节数,调用 readDatagram() 或 receiveDatagram() 可以读取数据报。

Note: An incoming datagram should be read when you receive the readyRead() signal, otherwise this signal will not be emitted for the next datagram.

注意:当你接收到 readyRead() 信号,一条刚到达的数据报就应要被读取,否则该信号在下个数据报到来时就不会被发射。

Example:

void Server::initSocket()
{
    udpSocket = new QUdpSocket(this);
    udpSocket->bind(QHostAddress::LocalHost, 7755);

    connect(udpSocket, SIGNAL(readyRead()),
    this, SLOT(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.

QUdpSocket类也支持UDP组播(组播:Server可以将数据包只发送给指定组内的客户端,而不发送给指定组外的客户端,也称多播)。可以用 joinMulticastGroup() 和 leaveMulticastGroup() 去控制管理组内的成员关系,QAbstractSocket::MulticastTtlOption 和 QAbstractSocket::MulticastLoopbackOption 可以设置TTL(Time To Live生存时间值)和socket回送选项。调用 setMulticastInterface() 可以为组播数据报管理外部接口,用 multicastInterface() 去查询。

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.

对于QUdpSocket,你也可以用 connectToHost() 与UDP服务器建立一个虚拟连接,然后用 read() 和 write()去交换数据报,而无需为每个数据报指定接收器。

The Broadcast Sender, Broadcast Receiver, Multicast Sender, and Multicast Receiver examples illustrate how to use QUdpSocket in applications.

如果在应用中使用QUdpSocket,在广播发送器,广播接收器,多播发送器和多播接收器的例子中都有说明。

二、QUdpSocket实际应用

1、udp服务端

  功能:1、接收来自客户端的数据  2、给客户端回送相关数据

  步骤:

    1、在.pro文件中添加网络模块  

QT += core gui network

    2、new一个QUdpSocket对象,并绑定端口号,为 readyRead() 连接信号槽

QUdpSocket *udpSocket = new QUdpSocket;
bool result = udpSocket->bind(29200);
qDebug()<<"#### socket bind result:"<<result<<" #####";
connect(udpSocket, SIGNAL(readyRead()), this, SLOT(recvData()));

    3、在槽函数中用 hasPendingDatagrams() 和 readDatagram() 接收数据

void MainWindow::recvData()
{
  while(udpSocket->hasPendingDatagrams())
  {
    QHostAddress srcAddress;

    QByteArray datagram;

    datagram.resize(udpSocket
->pendingDatagramSize());     udpSocket->readDatagram(datagram.data(), datagram.size(),&srcAddress);     QString msg = datagram.data();     qDebug()<<msg<<" ## "<<srcAddress;   } }

    4、用 writeDatagram() 发送数据

char data[2] = {0x01,0x02};
size = 2;
udpSocket->writeDatagram(data,size, QHostAddress("123.123.123.123"), 29234);    //要发送的目标ip和端口

2、udp客户端

  功能:1、给服务端发送相关数据  2、接收服务端回送相关数据

  从功能上看是完全与服务端一样的,因此实现方法也和服务端一致,只是绑定的端口是服务端调用 writeDatagram() 中的端口,发送的端口是服务端绑定的端口。

猜你喜欢

转载自www.cnblogs.com/qjswxd/p/11027189.html