1

我对 Qt 比较陌生,但我做了一些搜索。我有一个处理 UDP 广播的基类,并在类的构造函数中执行连接语句,如下所示:

NetworkConnection::NetworkConnection(QObject *parent)
    : QObject(parent) // Based on QObject
    , m_server_search( new QUdpSocket ) // Our UDP Broadcast socket
    , m_waiting_for_server( false )
    , m_found_server( false )
{
    qDebug() << "NetworkConnection::constructor";
    connect( m_server_search, SIGNAL(readyRead()), this, SLOT(serverResponse()), Qt::UniqueConnection );
    if ( m_server_search->bind( QHostAddress::AnyIPv4, (quint16)PORT_MULTICAST, QUdpSocket::ShareAddress ) )
    {
        if ( m_server_search->joinMulticastGroup( QHostAddress( MULTICAST_GROUP ) ) )
        {
            connect( this, SIGNAL(broadcast(NetworkMessage)), this, SLOT(broadcast_message(NetworkMessage)), Qt::UniqueConnection );
            this->m_ping_timer = this->startTimer(2000);
            qDebug() << "Ping timer id=" << this->m_ping_timer;
        } else qDebug() << "Couldn't start multicast listener";
    } else qDebug() << "Couldn't bind multicast to port" << PORT_MULTICAST;
}

我为广播设置了一个信号/插槽接口:

signals:
    void serverFound();
    void serverNotFound();
    void broadcast(NetworkMessage);

private slots:
    void serverResponse();
    void broadcast_message( NetworkMessage msg );

broadcast_message看起来像这样:

void NetworkConnection::broadcast_message( NetworkMessage msg )
{
    QByteArray raw = msg.toString();
    qDebug() << "NetworkConnection::broadcast_message>" << raw;
    if ( m_server_search->writeDatagram( raw.data(), raw.size(), QHostAddress(MULTICAST_GROUP), (quint16)PORT_MULTICAST ) < 1 ) qDebug() << "Failed broadcast last message";
}

我的计时器运行良好,代码如下:

void NetworkConnection::timerEvent(QTimerEvent *event)
{
    qDebug() << "NetworkConnection::timerEvent with id" << event->timerId() << "(ping timer=" << this->m_ping_timer << ")";
    if ( event->timerId() == this->m_ping_timer )
    {
        qDebug() << "NetworkConnection::pingForServer";
        if ( m_waiting_for_server && !m_found_server )
        {
            qDebug() << "Server not found!";
            emit this->serverNotFound();
            return;
        }
        if ( !m_found_server )
        {
            qDebug() << "Sending a ping to the server";
            NetworkMessage msg( m_software_guid, get_microseconds(), QString("whoisaserver") );
            emit this->broadcast( msg );
            m_waiting_for_server = true;
            m_found_server = false;
        }
    }
}

我只收到一次文本“向服务器发送一品脱”,但我的 broadcast_message 输出它qDebug()多次。

我没有明确地使用多个线程,正如你所看到的,我正在使用 Qt::UniqueConnection,这显然没有影响?

那么为什么会多次调用该插槽?我什至尝试过调试它,只调用 this->broadcast( ... ) 而不使用 emit,它仍然会被多次调用。

编辑:我刚刚在插槽中添加了一个计数器broadcast_message,它被调用了 340 次。这有什么意义吗?

4

0 回答 0