广播发送者
1 udpSocket = new QUdpSocket(this);
2
QByteArray datagram = "Broadcast message " + QByteArray::number(messageNo);
udpSocket->writeDatagram(datagram.data(), datagram.size(),QHostAddress::Broadcast, 45454);
//! [1]
++messageNo;
广播接收者
1
udpSocket = new QUdpSocket(this);
udpSocket->bind(45454, QUdpSocket::ShareAddress);
connect(udpSocket, SIGNAL(readyRead()),this, SLOT(processPendingDatagrams()));
2
void Receiver::processPendingDatagrams()
{
//! [2]
while (udpSocket->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(udpSocket->pendingDatagramSize());
udpSocket->readDatagram(datagram.data(), datagram.size());
statusLabel->setText(tr("Received datagram: \"%1\"")
.arg(datagram.data()));
}
//! [2]
}