我为 UDP 通信编写了以下简单程序:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
udpSocket = new QUdpSocket(this);
udpSocket->bind(QHostAddress::AnyIPv4, 4000);
connect(udpSocket, SIGNAL(readyRead()), this, SLOT(readDataFromSocket()));
udpSocket->writeDatagram("Test Data", QHostAddress("192.168.2.91"), 3000);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::readDataFromSocket()
{
while (udpSocket->hasPendingDatagrams()) {
udpSocket->receiveDatagram();
qDebug()<<"UDP data received";
}
}
现在的问题是,当我运行这个程序时,readyRead() 也会在发送数据时触发。几个有趣的发现:
我尝试将数据发送到网络上的不同 IP。对于少数 IP,它不会触发我的 readyRead() 函数。但是对于大多数 IP,readyRead() 确实会触发。
虽然 udpSocket->hasPendingDatagrams() 返回 true,但它没有任何数据。
我正在运行 Qt 5.12.3(MSVC 2017,32 位)。当我在 Qt 5.3.2(MSVC 2010,32 位)中运行相同的程序时,它工作正常,我的 readyRead() 永远不会触发。
任何人都可以帮忙吗?