void Widget::on_pushButton_clicked() { QUdpSocket *sender; sender = new QUdpSocket(this); QByteArray datagram = "hello world!"; sender->writeDatagram(datagram.data(),datagram.size(),QHostAddress("192.168.1.100"),45454); //sender->writeDatagram(datagram.data(),datagram.size(),QHostAddress::Broadcast,45454); // sender->writeDatagram(datagram.data(),datagram.size(),QHostAddress::LocalHost,45454); delete sender; }
This signal is emitted once every time new data is available for reading from the device. It will only be emitted again once new data is available, such as when a new payload of network data has arrived on your network socket, or when a new block of data has been appended to your device.
readyRead() is not emitted recursively; if you reenter the event loop or call waitForReadyRead() inside a slot connected to the readyRead() signal, the signal will not be reemitted (although waitForReadyRead() may still return true).
Note for developers implementing classes derived from QIODevice: you should always emit readyRead() when new data has arrived (do not emit it only because there's data still to be read in your buffers). Do not emit readyRead() in other conditions.
private: QUdpSocket *receiver; private slots: void processPendingDatagram();
receiver = new QUdpSocket(this); receiver->bind(45454,QUdpSocket::ShareAddress); connect(receiver,SIGNAL(readyRead()),this,SLOT(processPendingDatagram()));
void Widget::processPendingDatagram() //处理等待的数据报 { while(receiver->hasPendingDatagrams()) //拥有等待的数据报 { QByteArray datagram; //拥于存放接收的数据报 datagram.resize(receiver->pendingDatagramSize()); //让datagram的大小为等待处理的数据报的大小,这样才能接收到完整的数据 receiver->readDatagram(datagram.data(),datagram.size()); //接收数据报,将其存放到datagram中 ui->label->setText(datagram); //将数据报内容显示出来 } }