QT中使用UDP传输的核心代码:
void Sender::sendData()
{
if (!file.atEnd()) {
QByteArray line = file.read(8000);
udpSocket->writeDatagram( line , QHostAddress("192.168.0.175"),7755);
i++;
qDebug() << "send over!" << i << line.size();
}
}
void Sender::initSocket()
{
udpSocket = new QUdpSocket(this);
udpSocket->bind(QHostAddress::LocalHost, 7754);
connect(udpSocket, SIGNAL(readyRead()),
this, SLOT(readPendingDatagrams()));
}
void Sender::readPendingDatagrams()
{
//receive
while (udpSocket->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(udpSocket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
udpSocket->readDatagram(datagram.data(), datagram.size(),
&sender, &senderPort);
qDebug() << datagram;
if (datagram == "1")
{
qDebug() <<"send ok!";
sendData();
}
}
}
void Sender::on_pushButton_clicked()
{
fil