一、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().
當一個數據報被寫進了網絡中,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() 中的端口,發送的端口是服務端綁定的端口。