Raspberry Pi – Tutorial for Implementing UDP Transmission with Qt

What is UDP

My personal understanding of UP is a connectionless protocol. Before transmitting data, the receiving and sending ends do not establish a connection. When it wants to send, it simply grabs the data from the application and throws it onto the network as quickly as possible.

Simple to use, fast, but does not guarantee reliability.

Just send, regardless of whether you receive it.

Create a new project

Projects-> New Project -> Application -> Qt Widgets Application -> Choose

SetName : QtDemo_Udp

Edit UI

EditQtDemo_Udp\Forms\mainwindow.ui

Ø Drag twoLabel from Display Widgets, double-click to change the content toSend to IP and Send to Port

Raspberry Pi - Tutorial for Implementing UDP Transmission with Qt

Ø Drag twoLine Edit and oneText Edit from Input Widgets, and change the names of the twoLine Edit tolineEdit_Ip and lineEdit_Port, and change the name of theText Edit totextEdit_Msg

Raspberry Pi - Tutorial for Implementing UDP Transmission with Qt

Ø Drag twoPush Button from Buttons, and change the names of the twoPush Button topushButton_Send and pushButton_Stop, and change theirText properties toSend and Stop

Raspberry Pi - Tutorial for Implementing UDP Transmission with Qt

Edit QtDemo_Udp.pro

Change line 7 to QT += core gui network

#-------------------------------------------------## Project created by QtCreator 2019-05-17T05:54:52##-------------------------------------------------
QT       += core gui network
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = QtDemo_Udp
TEMPLATE = app
# The following define makes your compiler emit warnings if you use# any feature of Qt which has been marked as deprecated (the exact warnings# depend on your compiler). Please consult the documentation of the# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if you use deprecated APIs.# In order to do so, uncomment the following line.# You can also select to disable deprecated APIs only up to a certain version of Qt.#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += main.cpp\        mainwindow.cpp
HEADERS  += mainwindow.h
FORMS    += mainwindow.ui

Edit mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QUdpSocket> // Udp Socket
namespace Ui {class MainWindow;}
class MainWindow : public QMainWindow{    Q_OBJECT
public:    explicit MainWindow(QWidget *parent = 0);    ~MainWindow();
    void dealMsg();  // slot func
private:    Ui::MainWindow *ui;    QUdpSocket *udpSocket; // udp pointer};
#endif // MAINWINDOW_H

Add click response event to pushButton_Send

Add a new slot function in mainwindow.ui by right-clicking on the Send button and select Go to slotclick()

Raspberry Pi - Tutorial for Implementing UDP Transmission with Qt

Edit the slot function in mainwindow.cpp

void MainWindow::on_pushButton_Send_clicked(){    QString ip = ui->lineEdit_Ip->text();  // get the ip to send to    qint16 port = ui->lineEdit_Port->text().toInt(); // get the port
    QString msg = ui->textEdit_Msg->toPlainText(); // get the msg to send
    udpSocket->writeDatagram(msg.toUtf8(), QHostAddress(ip), port);}

Continue editing mainwindow.cpp

Modify function MainWindow::MainWindow

MainWindow::MainWindow(QWidget *parent) :    QMainWindow(parent),    ui(new Ui::MainWindow){    ui->setupUi(this);        // Allocate space, specify parent object    udpSocket = new QUdpSocket(this);        // Bind    udpSocket->bind(8888);
    // Get local ip    QString strIpAddress = QHostAddress(QHostAddress::LocalHost).toString();
    // Set window title    QString title = QString("Server IP:%1, port:8888").arg(strIpAddress);    setWindowTitle(title);
    // When the other party successfully sends data    // Automatically trigger readyRead()    connect(udpSocket, &QUdpSocket::readyRead, this, &MainWindow::dealMsg);    }

Add message handling function MainWindow::dealMsg()

// Message handling function
void MainWindow::dealMsg(){    char buf[512] = {0};    QHostAddress clientAddr;    quint16 port;
    // Read the content sent by the other party    qint64 len = udpSocket->readDatagram(buf, sizeof(buf), &clientAddr, &port);    if (len > 0) {        QString msg = QString("[%1:%2] %3")                .arg(clientAddr.toString())                .arg(port)                .arg(buf);
        // Set display content        ui->textEdit_Msg->setText(msg);
    }}

Test

Try sending a message to your own IP 127.0.0.1 Port 8888 or send a message to another computer.

Raspberry Pi - Tutorial for Implementing UDP Transmission with Qt

If you want to see a video demonstration? Just search for my account on Bilibili or check the comment link

Leave a Comment

×