在Qt中,可以使用QUdpSocket類(lèi)來(lái)發(fā)送和接收UDP數(shù)據(jù)。
發(fā)送UDP數(shù)據(jù):
QUdpSocket socket;
QHostAddress receiverAddress("127.0.0.1");
quint16 receiverPort = 12345;
QByteArray data = "Hello, World!";
socket.writeDatagram(data, receiverAddress, receiverPort);
接收UDP數(shù)據(jù):
QUdpSocket socket;
quint16 port = 12345;
if(!socket.bind(port)) {
qDebug() << "Failed to bind to port";
return;
}
connect(&socket, &QUdpSocket::readyRead, [&](){
while(socket.hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(socket.pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
socket.readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
qDebug() << "Received datagram from" << sender.toString() << ":" << senderPort;
qDebug() << "Data:" << datagram.data();
}
});
在上面的代碼中,我們首先創(chuàng)建一個(gè)QUdpSocket對(duì)象來(lái)發(fā)送和接收UDP數(shù)據(jù)。在發(fā)送數(shù)據(jù)時(shí),我們使用writeDatagram方法,傳入要發(fā)送的數(shù)據(jù)、接收方地址和端口號(hào)。在接收數(shù)據(jù)時(shí),我們首先綁定一個(gè)端口號(hào),然后通過(guò)readyRead信號(hào)來(lái)處理接收到的數(shù)據(jù)。我們可以使用hasPendingDatagrams方法來(lái)檢查是否有待處理的數(shù)據(jù)報(bào),再使用readDatagram方法讀取數(shù)據(jù)報(bào)的內(nèi)容、發(fā)送方地址和端口號(hào)。