QUdpSocket transmission



  • I try to run QT example "Broadcast Sender Example". (http://doc.qt.io/qt-5/qtnetwork-broa...r-example.html).
    It run without errors, but datagrams are not sended. And I have messages "QNativeSocketEngine::writeDatagram() was called not in QAbstractSocket::BoundState or QAbstractSocket::ConnectedState" in Application Output tab. Can anybode help me?

    sender.h

    #ifndef SENDER_H
    #define SENDER_H

    #include <QWidget>

    QT_BEGIN_NAMESPACE
    class QDialogButtonBox;
    class QLabel;
    class QPushButton;
    class QTimer;
    class QUdpSocket;
    QT_END_NAMESPACE

    class Sender : public QWidget
    {
    Q_OBJECT

    public:
    Sender(QWidget *parent = 0);

    private slots:
    void startBroadcasting();
    void broadcastDatagram();

    private:
    QLabel *statusLabel;
    QPushButton *startButton;
    QPushButton *quitButton;
    QDialogButtonBox *buttonBox;
    QUdpSocket *udpSocket;
    QTimer *timer;
    int messageNo;
    };

    #endif


    main.cpp

    #include <QApplication>

    #include "sender.h"

    int main(int argc, char *argv[])
    {
    QApplication app(argc, argv);
    Sender sender;
    sender.show();
    return app.exec();
    }


    sender.cpp

    #include <QtWidgets>
    #include <QtNetwork>

    #include "sender.h"

    Sender::Sender(QWidget *parent)
    : QWidget(parent)
    {
    statusLabel = new QLabel(tr("Ready to broadcast datagrams on port 45454"));
    statusLabel->setWordWrap(true);

    startButton = new QPushButton(tr("&Start"));
    quitButton = new QPushButton(tr("&Quit"));

    buttonBox = new QDialogButtonBox;
    buttonBox->addButton(startButton, QDialogButtonBox::ActionRole);
    buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole);

    timer = new QTimer(this);
    //! [0]
    udpSocket = new QUdpSocket(this);
    //! [0]
    messageNo = 1;

    connect(startButton, SIGNAL(clicked()), this, SLOT(startBroadcasting()));
    connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
    connect(timer, SIGNAL(timeout()), this, SLOT(broadcastDatagram()));

    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addWidget(statusLabel);
    mainLayout->addWidget(buttonBox);
    setLayout(mainLayout);

    setWindowTitle(tr("Broadcast Sender"));
    }

    void Sender::startBroadcasting()
    {
    startButton->setEnabled(false);
    timer->start(1000);
    }

    void Sender::broadcastDatagram()
    {
    statusLabel->setText(tr("Now broadcasting datagram %1").arg(messageNo));
    //! [1]
    QByteArray datagram = "Broadcast message " + QByteArray::number(messageNo);
    udpSocket->writeDatagram(datagram.data(), datagram.size(),
    QHostAddress::Broadcast, 45454);
    //! [1]
    ++messageNo;
    }



  • Hi @Slavius

    On some machines you will have to allow trafic in the firewall.

    -Michael.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.