Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write the sample code for QT5 to implement UDP communication?

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

QT5 to achieve UDP communication sample code how to write, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can get something.

Preface

This routine has been verified to work normally, simply using the unicast mode in UDP (one-to-one), and the rest will be explained step by step at a later stage.

The test system used is on the same local area network, where:

QT version: 5.12

PC UDP mode: unicast

UDP communication goal: Ethernet interface based on STM32F4+LWIP protocol

I. Overview of UDP Communications

UDP is a lightweight, unreliable, Datagram-oriented, connectionless protocol. It can be used in situations that do not require high reliability. Unlike TCP communication, UDP communication between the two programs does not need to establish a lasting socket connection in advance. UDP needs to specify the target address and port every time it sends a Datagram.

The QUdpSocket class is used to implement UDP communication. The writeDatagram () function is used to send datagrams. The length of datagrams is generally less than 512 bytes, and each Datagram contains information such as the IP address and port of the sender and receiver. The receiving Datagram must first bind a port with the bind () function. When there is data coming in, it will trigger the readyRead signal and use the readDatagram () function to read the received data.

Second, UDP unicast mode

The realization of this paper is that the upper computer (PC) sends information to the lower computer (STM32). After receiving the information, the STM32 immediately returns a frame of information. After the upper computer receives the information, the parsing command gets the IP address and port number of the lower computer, and prints with the information content.

First add QT + = network to the .pro file of QT.

1. Receive data

To receive UDP data, you must first bind a local port with the bind () function to listen for incoming datagrams, and unbind it using the abort () function. After the port is bound, the readyRead () signal in the QUdpSocket class is triggered when the data is received by the host computer, so the signal is connected to the UDPSocketReadyRead () function through the slot function to process the received data.

/ * * receive data * / void MainWindow::UDPSocketReadyRead () {while (Myudpsocket- > hasPendingDatagrams ()) {QByteArray Recivedata; Recivedata.resize (Myudpsocket- > pendingDatagramSize ()); QHostAddress peerAddr; quint16 peerPort; Myudpsocket- > readDatagram (Recivedata.data (), Recivedata.size (), & peerAddr, & peerPort); QString str = Recivedata.data () QString peer = "[From" + peerAddr.toString () + ":" + QString::number (peerPort) + "]"; ui- > textEdit_recive- > setText (peer+str);}} 2. Send data

When you use the writeDatagram () function to send a message to the lower computer, you need to specify the destination address and port. The Datagram sent by QUdpSocket is of QByteArray type and is generally no more than 512 bytes in length.

/ * * send data * / void MainWindow::on_pushButton_UDP_send_clicked () {QHostAddress GoalADDr (QString (ui- > comboBox_goalIP- > currentText ()); quint16 GoalPort = ui- > spinBox_goalport- > value (); QString sendstr = ui- > textEdit_send- > toPlainText (); QByteArray str = sendstr.toUtf8 (); Myudpsocket- > writeDatagram (str, GoalADDr, GoalPort); / / ui- > label_information- > setText ("send ok!");} Summary

The following code has been verified and can be used normally!

Code h file

# ifndef MAINWINDOW_H#define MAINWINDOW_H#include # include namespace Ui {class MainWindow;} class MainWindow: public QMainWindow {Q_OBJECTpublic: explicit MainWindow (QWidget * parent = nullptr); ~ MainWindow (); private slots: void UDPSocketReadyRead (); void on_pushButton_UDP_send_clicked (); void on_pushButton_UDP_bind_clicked (); private: Ui::MainWindow * ui; QString GetlocalIP (); QUdpSocket * Myudpsocket;} # endif / / MAINWINDOW_H code c file

# include "mainwindow.h" # include "ui_mainwindow.h" MainWindow::MainWindow (QWidget * parent): QMainWindow (parent), ui (new Ui::MainWindow) {ui- > setupUi (this); / * obtain the native IP address * / QString localIP = GetlocalIP (); this- > setWindowTitle ("--Native IP:" + localIP); ui- > comboBox_localIP- > addItem (localIP) / * Native IP settings * / Myudpsocket = new QUdpSocket (this); connect (Myudpsocket, & QUdpSocket::readyRead, this, & MainWindow::UDPSocketReadyRead);} MainWindow::~MainWindow () {Myudpsocket- > abort (); / / unbind delete ui;} / * * obtain native IP address * / QString MainWindow::GetlocalIP () {QString strIpAddress; QList ipAddressesList = QNetworkInterface::allAddresses () / / obtain the IPv4 address of the first local host int nListSize = ipAddressesList.size (); for (int I = 0; I

< nListSize; ++i) { if (ipAddressesList.at(i) != QHostAddress::LocalHost && ipAddressesList.at(i).toIPv4Address()) { strIpAddress = ipAddressesList.at(i).toString(); break; } } // 如果没有找到,则以本地IP地址为IP if (strIpAddress.isEmpty()) strIpAddress = QHostAddress(QHostAddress::LocalHost).toString(); return strIpAddress;}/** 接收数据*/void MainWindow::UDPSocketReadyRead(){ while(Myudpsocket->

HasPendingDatagrams () {QByteArray Recivedata; Recivedata.resize (Myudpsocket- > pendingDatagramSize ()); QHostAddress peerAddr; quint16 peerPort; Myudpsocket- > readDatagram (Recivedata.data (), Recivedata.size (), & peerAddr, & peerPort); QString str = Recivedata.data (); QString peer = "[From" + peerAddr.toString () + ":" + QString::number (peerPort) + "]" Ui- > textEdit_recive- > setText (peer+str);}} / * * send data * / void MainWindow::on_pushButton_UDP_send_clicked () {QHostAddress GoalADDr (ui- > comboBox_goalIP- > currentText ()); quint16 GoalPort = ui- > spinBox_goalport- > value (); QString sendstr = ui- > textEdit_send- > toPlainText (); QByteArray str = sendstr.toUtf8 (); Myudpsocket- > writeDatagram (str, GoalADDr, GoalPort) / / ui- > label_information- > setText ("send ok!");} / * * bind port * / void MainWindow::on_pushButton_UDP_bind_clicked () {quint16 port = ui- > spinBox_localport- > value (); if (Myudpsocket- > bind (port)) {ui- > label_information- > setText (QString ("Port number:% 1 bind successfully") .arg (port)) } else {ui- > label_information- > setText (QString ("Port number:% 1 binding failed") .arg (port));}} is it helpful for you to read the above? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

  • How to realize title display date by JavaScript

    This article mainly introduces JavaScript how to achieve title display date, the article is very detailed, has a certain reference value, interested friends must read it! Title displays the date by adding the following code to the area:

    © 2024 shulou.com SLNews company. All rights reserved.

    12
    Report