栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

Qt udp编程

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Qt udp编程

初始化udpSocket
QUdpSocket * udpSocket = new QUdpSocket(this);
绑定本地端口
quint64 port = ui->localPort->text().toUInt();
udpSocket->bind(port);
关联readyRead信号
connect(udpSocket, &QUdpSocket::readyRead, this, &UdpDemo::readyRead_slot);
实现readyRead_slot槽函数
void UdpDemo::readyRead_slot()
{
    while(udpSocket->hasPendingDatagrams())
    {

        QHostAddress addr;
        quint16 port;


        QByteArray array;
        array.resize(udpSocket->pendingDatagramSize());

        udpSocket->readDatagram(array.data(), array.size(), &addr, &port);

        QString buf;
        buf = array.data();
        showMsg(QString("%1:%2-> %3").arg(IPV4IntegerToString(addr.toIPv4Address())).arg(port).arg(buf));

    }
}
发送数据报
quint16 port;

QHostAddress address;

QString targetIp = ui->targetIp->text();
if (targetIp.isEmpty())
{
    QMessageBox::warning(this, "提示", "远程IP不能为空!", "确定");
    return ;
}
address.setAddress(targetIp);

ui->sendEdit->clear();
port = ui->targetPort->text().toUInt();
udpSocket->writeDatagram(sendbuff.toLocal8Bit().data(), sendbuff.length(), address, port);
完整项目代码 udpDemo.pro
QT       += core gui network

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11

# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked 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 it uses 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 
    udpdemo.cpp

HEADERS += 
    udpdemo.h

FORMS += 
    udpdemo.ui

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

udpdemo.h
#ifndef UDPDEMO_H
#define UDPDEMO_H

#include 
#include 
#include 
#include 
#include 
#include 

QT_BEGIN_NAMESPACE
namespace Ui { class UdpDemo; }
QT_END_NAMESPACE

class UdpDemo : public QMainWindow
{
    Q_OBJECT

public:
    QUdpSocket *udpSocket;
    bool isOpen;

public:
    UdpDemo(QWidget *parent = nullptr);
    ~UdpDemo();

    void showMsg(const QString &str);

    QString IPV4IntegerToString(quint32 ip);

    quint32 IPV4StringToInteger(const QString& ip);

private slots:
    void on_openBtn_clicked();

    void readyRead_slot();

    void on_sendBtn_clicked();

    void on_closeBtn_clicked();



private:
    Ui::UdpDemo *ui;
};
#endif // UDPDEMO_H

udpdemo.cpp
#include "udpdemo.h"
#include "ui_udpdemo.h"

UdpDemo::UdpDemo(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::UdpDemo)
    , udpSocket(new QUdpSocket(this))
    , isOpen(false)
{
    ui->setupUi(this);

    ui->closeBtn->setEnabled(false);
    ui->sendBtn->setEnabled(false);
}

UdpDemo::~UdpDemo()
{
    delete ui;
}

void UdpDemo::showMsg(const QString &str)
{
    ui->recvEdit->appendPlainText(QTime::currentTime().toString("[HH:mm:ss] %1").arg(str));
}


void UdpDemo::on_openBtn_clicked()
{
    if (!udpSocket->isOpen())
    {
        quint64 port = ui->localPort->text().toUInt();
        udpSocket->bind(port);
        connect(udpSocket, &QUdpSocket::readyRead, this, &UdpDemo::readyRead_slot);
        showMsg(QString("绑定本地端口号:%1").arg(port));
        isOpen = true;
        ui->sendBtn->setEnabled(true);
        ui->closeBtn->setEnabled(true);
        ui->openBtn->setEnabled(false);
    } else
    {
        QMessageBox::information(this, "提示", "本地端口已打开!", "确定");
        return ;
    }

}

void UdpDemo::readyRead_slot()
{
    while(udpSocket->hasPendingDatagrams())
    {

        QHostAddress addr;
        quint16 port;


        QByteArray array;
        array.resize(udpSocket->pendingDatagramSize());

        udpSocket->readDatagram(array.data(), array.size(), &addr, &port);

        QString buf;
        buf = array.data();
        showMsg(QString("%1:%2-> %3").arg(IPV4IntegerToString(addr.toIPv4Address())).arg(port).arg(buf));

    }
}

void UdpDemo::on_sendBtn_clicked()
{
    if (!isOpen)
    {
        QMessageBox::warning(this, "提示", "没有打开的端口!","确定");
        return;
    }

    QString sendbuff = ui->sendEdit->toPlainText();
    if (sendbuff.isEmpty())
    {
        QMessageBox::information(this, "提示", "发送内容不能为空!","确定");
        return;
    }
    quint16 port;

    QHostAddress address;

    QString targetIp = ui->targetIp->text();
    if (targetIp.isEmpty())
    {
        QMessageBox::warning(this, "提示", "远程IP不能为空!", "确定");
        return ;
    }
    address.setAddress(targetIp);

    ui->sendEdit->clear();
    port = ui->targetPort->text().toUInt();

    udpSocket->writeDatagram(sendbuff.toLocal8Bit().data(), sendbuff.length(), address, port);

    showMsg(QString("%1:%2<- %3").arg(IPV4IntegerToString(address.toIPv4Address())).arg(port).arg(sendbuff));
}

void UdpDemo::on_closeBtn_clicked()
{
    if (isOpen)
    {
        udpSocket->close();
        ui->sendBtn->setEnabled(false);
        ui->closeBtn->setEnabled(false);
        ui->openBtn->setEnabled(true);
        showMsg("端口已关闭");
    }
    isOpen = false;


}



QString UdpDemo::IPV4IntegerToString(quint32 ip) {
    return QString("%1.%2.%3.%4")
            .arg((ip >> 24) & 0xFF)
            .arg((ip >> 16) & 0xFF)
            .arg((ip >> 8) & 0xFF)
            .arg(ip & 0xFF);
}

quint32 UdpDemo::IPV4StringToInteger(const QString& ip){
   QStringList ips = ip.split(".");
   if(ips.size() == 4){
       return ips.at(3).toInt()
               | ips.at(2).toInt() << 8
               | ips.at(1).toInt() << 16
               | ips.at(0).toInt() << 24;
   }
   return 0;
}

UI界面

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/938010.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号