Qt UDP Guide: Send & Receive Data
To implement UDP data sending and receiving in Qt, you need to use the QUdpSocket class. Here is a simple example code:
// 创建一个QUdpSocket对象
QUdpSocket *udpSocket = new QUdpSocket(this);
// 绑定本地端口用于接收数据
udpSocket->bind(QHostAddress::Any, 1234);
// 发送数据
udpSocket->writeDatagram("Hello UDP", QHostAddress::LocalHost, 1234);
// 接收数据
connect(udpSocket, &QUdpSocket::readyRead, this, [=](){
QByteArray datagram;
datagram.resize(udpSocket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
qDebug() << "Received datagram: " << datagram;
qDebug() << "From: " << sender.toString() << ":" << senderPort;
});
In the given code, a QUdpSocket object udpSocket is first created and bound to local port 1234 to receive data. Data is then sent to the local host’s port 1234 using the writeDatagram method. The data is received by connecting to the signal readyRead, obtaining the data size from pendingDatagramSize(), reading the data using readDatagram method, and then printing out the received data along with the sender’s IP address and port number.