我在我的 QUdpSocket 上收到了两次数据报,即使我正在看 wireshark 并且它只收到一次。我创建了套接字并在端口 11112 上侦听。还有另一个设备在我正在侦听的此端口上发出数据。对于发送的每条实际消息,我始终收到两条消息。我不确定是什么原因造成的。有什么想法吗?
精简代码:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_socket = new QUdpSocket(this);
connect (m_socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(onSocketStateChange(QAbstractSocket::SocketState)));
m_socket->bind(11112, QUdpSocket::ShareAddress);
}
MainWindow::~MainWindow()
{
delete ui;
delete m_socket;
}
void MainWindow::readPendingDatagrams()
{
QByteArray buffer;
QHostAddress sender;
quint16 port;
while(m_socket->hasPendingDatagrams())
{
int s = m_socket->pendingDatagramSize();
buffer.resize(s);
//for some reason there are two datagrams on the line.
// I have verified with wireshark that there is only one from the
// sender so not sure what is happening under the hood...
m_socket->readDatagram(buffer.data(),buffer.size(),&sender, &port);
QString source = sender.toString().split(":")[3];
if (source == "172.20.23.86")
{
qInfo() << buffer <<endl;
}
}
}
void MainWindow::onSocketStateChange(QAbstractSocket::SocketState state)
{
if ( state == QAbstractSocket::BoundState ) {
connect(m_socket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));
}
}