Qt actual combat case (30) -- using QUdpSocket class to realize UDP network broadcast communication

Posted by RandomEngy on Tue, 25 Jan 2022 04:17:25 +0100

1, Project introduction

UDP network broadcast communication is realized by using QUdpSocket class. Its principle is shown in the figure below.

The working principle of UDP is: the UDP client sends a certain length of request message to the UDP server. The message size limit is related to the protocol implementation of each system, but it shall not exceed 64KB specified by its lower IP; The UDP server also responds in the form of message. If the server does not receive this request, the client will not resend, so the message transmission is unreliable. This is the main disadvantage of UDP.

2, Project basic configuration

Create a new Qt case, the project name is "Server", the base class is "QDialog", and the class name is "Server". Uncheck the check box of create UI interface to complete the project creation. [the project is a UDP Server, see 4.1 and 4.2 for details]
Create another Qt case. The project name is "Client", the base class is "QDialog", and the class name is "Client". Uncheck the check box of create UI interface to complete the project creation. [this project is a UDP Client, see 4.3 and 4.4 for details]

3, UI interface design

No UI interface

4, Main program implementation

4.0 pro files

First, you need to add the following code to the two pro files:

QT+=network

4.1 server.h header file

Private variables and some slot functions are declared in the header file:

public slots:
    void StartBtnClicked();//Button click slot function
    void timeout();

private:
    QLabel *TimerLabel;
    QLineEdit *TextLineEdit;
    QPushButton *StartBtn;
    QVBoxLayout *mainLayout;

    int port;
    bool isStarted;
    QUdpSocket *udpSocket;
    QTimer *timer;

4.2 server.cpp source file

Create the interface and set the corresponding layout:

    /*Create interface*/
    setWindowTitle(tr("UDP Server")) ;//Sets the title of the form
    //Initialize each control
    TimerLabel = new QLabel(tr("timer:"),this);
    TextLineEdit= new QLineEdit(this);
    StartBtn = new QPushButton(tr("start"),this);
    //Set layout
    mainLayout= new QVBoxLayout (this);
    mainLayout->addWidget(TimerLabel);
    mainLayout->addWidget(TextLineEdit);
    mainLayout->addWidget(StartBtn);

Set the slot function of the connection:

    connect(StartBtn,SIGNAL(clicked()),this, SLOT(StartBtnClicked()));//Click the start button corresponding to the slot function
    port= 5555;    //Set the port number parameter of UDP, and the server sends broadcast information to this port regularly
    isStarted = false;
    udpSocket = new QUdpSocket(this);//Create a new QUdpSocket
    timer = new QTimer(this);
    //Regularly send broadcast information
    connect(timer,SIGNAL(timeout()),this,SLOT(timeout()));

Click the slot function button:

void Server::StartBtnClicked()
{
    if(!isStarted)
    {
        StartBtn->setText(tr("stop it"));
        timer->start(1000);//The time interval is 1000ms
        isStarted=true;
    }else{
        StartBtn->setText (tr("start"));
        isStarted = false;
        timer->stop();
    }
}

Send broadcast slot function:

//Send broadcast information to port
void Server::timeout()
{
    QString msg= TextLineEdit->text();//Get the text content to be sent
    int length=0;
    if (msg=="")
    {
        return;
    }
    //Send broadcast msg
    if((length=udpSocket->writeDatagram(msg.toLatin1(),
    msg.length(),QHostAddress::Broadcast,port))!=msg.length())
    {
        return;
    }
}

4.3 client.h header file

Private variables and some slot functions are declared in the header file:

public slots:
    void dataReceived();
private:
    QTextEdit *ReceiveTextEdit;
    QPushButton *CloseBtn;
    QVBoxLayout *mainLayout;

    int port;
    QUdpSocket *udpSocket;

4.4 client.cpp source file

First, create the interface and set the corresponding layout:

    setWindowTitle(tr("UDP Client")); //Sets the title of the form
    //Initialize individual controls
    ReceiveTextEdit= new QTextEdit(this) ;
    CloseBtn = new QPushButton(tr ("Close"),this) ;
    //Set layout
    mainLayout=new QVBoxLayout(this) ;
    mainLayout->addWidget(ReceiveTextEdit);
    mainLayout->addWidget(CloseBtn);

Set up corresponding connection to receive broadcast information:

    connect (CloseBtn, SIGNAL (clicked()), this, SLOT (close()));//close
    port =5555;    //Set the port number parameter of UDP and specify to listen for data on this port
    udpSocket = new QUdpSocket (this); //Create a QudpSocket
    connect (udpSocket, SIGNAL(readyRead()), this, SLOT (dataReceived())) ;//When data reaches the IO device, the dataReceived() function is triggered
    bool result=udpSocket->bind(port);//Bind to the specified port
    if(!result)
    {
        QMessageBox::information(this, tr("error"), tr ("udp socket create error!"));
        return;
    }

Receive broadcast slot function:

//Once the data is readable, the data is read and displayed through the readDatagram method
void Client::dataReceived()
{
    while(udpSocket->hasPendingDatagrams())    //Determine whether the udpSocket has data waiting to be read
    {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());//Resize
        udpSocket->readDatagram(datagram.data(), datagram.size());//Read the length of the first datagram
        QString msg=datagram.data();
        ReceiveTextEdit-> insertPlainText(msg);    //Display data content
    }
}

5, Effect demonstration

Run these two Qt programs at the same time, and the complete effects are as follows:

If you don't understand it, you can refer to the complete code: https://download.csdn.net/download/didi_ya/77497306

ok, that's all the content of this article. If it's helpful to you, remember to like it~

Topics: C++ network Qt Network Protocol udp