各位大佬们好,本人QT小白一枚
最近学QT socket的时候发现了一个奇异的现象,大致情况如下:
构造函数中创建了一个udp套接字,该套接字绑定了本机的ip(本机ip即为“192.168.18.125”,端口为14551),如下所示;
udpSock = new QUdpSocket(this);
udpSock->bind(QHostAddress("192.168.18.125"), 14551);
heartTimer = new QTimer(this);
heartTimer->setInterval(100);
heartTimer->start();
connect(udpSock, SIGNAL(readyRead()), this, SLOT(receive())); connect(heartTimer, SIGNAL(timeout()), this, SLOT(sendDatagram()));
并且让该套接字定时发送消息给本机ip的另一个端口(即192.168.18.125:15551),如下所示;
void Widget::sendDatagram(){
QByteArray ba;
ba.resize(5);
ba[0] = 0x3c;
ba[1] = 0xb8;
ba[2] = 0x64;
ba[3] = 0x18;
ba[4] = 0xca;
udpSock->writeDatagram(ba, QHostAddress("192.168.18.125"), 15551);
}
但是发现套接字虽然并没有给 192.168.18.125(本机ip):14551 发送数据,但是这个套接字却一直发射readyRead()信号,如下所示;
void Widget::receive(){
QByteArray ba;
while(udpSock->hasPendingDatagrams())
{
ba.resize(udpSock->pendingDatagramSize());
udpSock->readDatagram(ba.data(), ba.size());
qDebug()<<"udpSock->hasPendingDatagrams()"<<ba.data()<<endl; //会一直运行这段代码
}
}
但是如果我开一个网络调试助手接收192.168.18.125:15551的数据,这个套接字就不发射readyRead()信号;
这个问题困惑了我很久,希望大佬可以指点迷津~