Qt 8. UDP客户端通信

1. 代码
//UdpClient.h
#ifndef UDPCLIENT_H
#define UDPCLIENT_H

#include 

class Ex2;      // 声明类
class UdpClient : public QObject
{
    Q_OBJECT
public:
    explicit UdpClient(Ex2 *ui = nullptr);
    ~UdpClient();
    void Send(QByteArray buf,QHostAddress addr, int port);
    void Send(char *buf,int length,QHostAddress addr, int port);
    void Send(char *buf,int length);
    void Send(QByteArray buf);
    void Receive();
    bool Close();
    bool Open(QString ip,int port);
    void SaveIpPort(QHostAddress ip,int port);
private:
    Ex2 *pUi;
    QUdpSocket *socket;
    QHostAddress addr;
    int port;
signals:

};

#endif // UDPCLIENT_H
//UdpClient.cpp
#include "UdpClient.h"
#include "ex2.h"
#include "ui_ex2.h"

UdpClient::UdpClient(Ex2 *ui)
{
    socket = new QUdpSocket();
    pUi = ui;
    connect(socket,&QUdpSocket::readyRead,this,&UdpClient::Receive);
}

UdpClient::~UdpClient()
{
    delete socket;
}

bool UdpClient::Open(QString ip,int port)
{
    socket->close();/*取消绑定端口号使用:udpsocket->close()方法*/
    QHostAddress ipAddr = QHostAddress(ip);
    SaveIpPort(ipAddr,port);
    socket->bind(ipAddr,port);
    return true;
}

bool UdpClient::Close()
{
    socket->close();
    return true;
}

void UdpClient::SaveIpPort(QHostAddress ipAddr,int ipPort)
{
    addr = ipAddr;
    port = ipPort;
}

void UdpClient::Send(char *buf,int length,QHostAddress addr, int port)
{
    QByteArray arr(buf,length);
    socket->writeDatagram(arr,addr,port);
    socket->flush();
}

void UdpClient::Send(char *buf,int length)
{
    QByteArray arr(buf,length);
    socket->writeDatagram(arr,addr,port);
    socket->flush();
}

void UdpClient::Send(QByteArray buf,QHostAddress addr, int port)
{
    socket->writeDatagram(buf,addr,port);
    socket->flush();
}

void UdpClient::Send(QByteArray buf)
{
    socket->writeDatagram(buf,addr,port);
    socket->flush();
}

//12 34 A1 A2 -> "12 34 A1 A2"
QString ByteArrayToHexString(QByteArray data)
{
    QString ret(data.toHex().toUpper());
    int len = ret.length()/2;
    for(int i=1;i<len;i++)
    {
        ret.insert(2*i+i-1," ");
    }

    return ret;
}

void UdpClient::Receive()
{

    QHostAddress addr; //用于获取发送者的 IP 和端口
    quint16 port;
    //数据缓冲区
    QByteArray buffer;
    while(socket->hasPendingDatagrams())
    {
        //调整缓冲区的大小和收到的数据大小一致
        buffer.resize(socket->bytesAvailable());

        //接收数据
        socket->readDatagram(buffer.data(),buffer.size(),&addr,&port);
        //显示
        QString str0 = ByteArrayToHexString(buffer) +" ";
        if(!buffer.isEmpty())
        {
            QString str = pUi->ui->textEditMy1->toPlainText();
            str += str0;
            //刷新显示
            pUi->ui->textEditMy1->setText(str);
        }
    }
}
//Ex2.cpp
#include "ex2.h"
#include "ui_ex2.h"

int static cnt = 0;

Ex2::Ex2(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Ex2)
{
ui->setupUi(this);

....
    //UDP
    udpClientSocket = new UdpClient(this);
    ui->lineEditUdpIp->setText("192.168.9.123");
    ui->lineEditUdpPort->setText("6000");
}

void Ex2::on_pushButtonUdpConnect_clicked()
{
    if(ui->pushButtonUdpConnect->text()==tr("创建"))
    {
        if(udpClientSocket->Open(ui->lineEditUdpIp->text(),ui->lineEditUdpPort->text().toInt()) == true)
        {
            ui->pushButtonUdpConnect->setText("取消");
        }
    }
    else
    {
        udpClientSocket->Close();
        ui->pushButtonUdpConnect->setText("创建");
    }
}

void Ex2::on_pushButtonUdpSend_clicked()
{
    //获取文本框内容并以ASCII码形式发送
    uchar buf[13];
    int i=0;
    buf[i++] = 0xAA;
    buf[i++] = 0x55;
    buf[i++] = 0xAA;
    udpClientSocket->Send((char *)buf,i);
}
//Ex2.h
#ifndef EX2_H
#define EX2_H

#include 

#include 
#include 
#include ".\UDP\UdpClient.h"


QT_BEGIN_NAMESPACE
namespace Ui { class Ex2; }
QT_END_NAMESPACE

class Ex2 : public QDialog
{
    Q_OBJECT

public:
    Ex2(QWidget *parent = nullptr);
    ~Ex2();
    Ui::Ex2 *ui;
    UdpClient *udpClientSocket;

private slots:
    void on_pushButtonUdpConnect_clicked();

    void on_pushButtonUdpSend_clicked();

private:
    //Ui::Ex2 *ui;
    QSerialPort *serial;
};
#endif // EX2_H
2. 效果

以上代码可以实现UDP收发功能。
在这里插入图片描述

你可能感兴趣的:(Qt,qt,udp,开发语言)