QUdpSocket-数据报被接收两次,为什么?

时间:2018-11-01 18:02:14

标签: c++ qt qt5 qudpsocket

即使我在Wireshark上观看,我也在QUdpSocket上两次接收到一个数据报,并且只收到一次。我创建了套接字,并在端口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()));
       }

}

2 个答案:

答案 0 :(得分:1)

如果将数据报发送到广播地址,并且您绑定到所有接口(0.0.0.0),并且有两个接口接收数据报,则可能会发生这种情况。为了排除这种可能性,请切换到receiveDatagram API并转储您收到的数据报的全部详细信息。我敢打赌,您每次收到的界面都会不同。

您还可能多次连接readPendingDatagrams插槽,因此可能会触发多次,尽管hasPendingDatagrams应该第二次返回false-因此尽管这可能不是 the 问题,而是必须解决的 a 问题。只能连接一次-在构造套接字时,即在构造函数中。

答案 1 :(得分:0)

Unslander Monica 是正确的,它默认绑定所有接口,可以通过 m_socket->bind(QHostAddress::LocalHost,11112);