QUdpSocket使用整理

效果图
这里写图片描述

服务端源码
注意:在.pro中添加QT += network

udpserver.h

#ifndef UDPSERVER_H
#define UDPSERVER_H

#include <QDialog>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QVBoxLayout>
#include <QUdpSocket>
#include <QTimer>

class UdpServer : public QDialog
{
    Q_OBJECT

public:
    UdpServer(QWidget *parent = 0,Qt::WindowFlags f=0);
    ~UdpServer();
public slots:
    void StartBtnClicked();//点击开始按钮
    void timeout();//一段时间后执行函数
private:
    QLabel *TimerLabel;
    QLineEdit *TextLineEdit;//发送内容的lineedit
    QPushButton *StartBtn;//开始按钮
    QVBoxLayout *mainLayout;//布局
    int port;//端口号
    bool isStarted;//是否开始
    QUdpSocket *udpSocket;//udp
    QTimer *timer;//计时器
};

#endif // UDPSERVER_H

udpserver.cpp

#include "udpserver.h"
#include <QHostAddress>

UdpServer::UdpServer(QWidget *parent, Qt::WindowFlags f)
    : QDialog(parent,f)
{
    setWindowTitle(tr("UDP Server"));

    TimerLabel = new QLabel(tr("计时器:"),this);
    TextLineEdit = new QLineEdit(this);
    StartBtn = new QPushButton(tr("开始"),this);

    mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(TimerLabel);
    mainLayout->addWidget(TextLineEdit);
    mainLayout->addWidget(StartBtn);

    connect(StartBtn,SIGNAL(clicked()),this,SLOT(StartBtnClicked()));

    port =5555;
    isStarted=false;
    udpSocket = new QUdpSocket(this);
    timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(timeout()));
}

UdpServer::~UdpServer()
{

}

void UdpServer::StartBtnClicked()
{
    if(!isStarted)
    {
        StartBtn->setText(tr("停止"));
        timer->start(1000);//每1秒执行一次timeout()
        isStarted =true;
    }
    else
    {
        StartBtn->setText(tr("开始"));
        isStarted = false;
        timer->stop();//停止
    }
}

void UdpServer::timeout()
{
    QString msg = TextLineEdit->text();
    int length=0;
    if(msg=="")
    {
       return;
    }
    //通过udp写入传输数据
    if((length=udpSocket->writeDatagram(msg.toLatin1(),msg.length(),QHostAddress::Broadcast,port))!=msg.length())
    {
        return;
    }
}

客户端源码
注意:在.pro中添加QT += network
udpclient.h

#ifndef UDPCLIENT_H
#define UDPCLIENT_H

#include <QDialog>
#include <QVBoxLayout>
#include <QTextEdit>
#include <QPushButton>
#include <QUdpSocket>

class UdpClient : public QDialog
{
    Q_OBJECT

public:
    UdpClient(QWidget *parent = 0,Qt::WindowFlags f=0);
    ~UdpClient();    
public slots:
    void CloseBtnClicked();//点击关闭按钮
    void dataReceived();//点击接受按钮
private:
    QTextEdit *ReceiveTextEdit;//接受的内容
    QPushButton *CloseBtn;//关闭
    QVBoxLayout *mainLayout;//布局
    int port;//端口号
    QUdpSocket *udpSocket;//udp
};

#endif // UDPCLIENT_H

udpclient.cpp

#include "udpclient.h"
#include <QMessageBox>
#include <QHostAddress>

UdpClient::UdpClient(QWidget *parent,Qt::WindowFlags f)
    : QDialog(parent,f)
{
    setWindowTitle(tr("UDP Client"));

    ReceiveTextEdit = new QTextEdit(this);
    CloseBtn = new QPushButton(tr("Close"),this);

    mainLayout=new QVBoxLayout(this);
    mainLayout->addWidget(ReceiveTextEdit);
    mainLayout->addWidget(CloseBtn);

    connect(CloseBtn,SIGNAL(clicked()),this,SLOT(CloseBtnClicked()));

    port =5555;

    udpSocket = new QUdpSocket(this);
    connect(udpSocket,SIGNAL(readyRead()),this,SLOT(dataReceived()));

    bool result=udpSocket->bind(port);
    //当绑定失败时弹出提示
    if(!result)
    {
        QMessageBox::information(this,tr("error"),tr("udp socket create error!"));
        return;
    }
}

UdpClient::~UdpClient()
{

}

void UdpClient::CloseBtnClicked()
{
    close();
}

void UdpClient::dataReceived()
{
    //通过udp接收数据
    while(udpSocket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        //读取数据
        udpSocket->readDatagram(datagram.data(),datagram.size());
        QString msg=datagram.data();
        //向textdit中插入数据
        ReceiveTextEdit->insertPlainText(msg);
    }
}
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
QUdpSocket是Qt中用于实现UDP网络编程的类,可以用于发送和接收UDP数据包。以下是使用QUdpSocket进行UDP网络编程的基本步骤: 1. 引入头文件:在使用QUdpSocket之前,需要在代码中引入头文件: ```c++ #include <QUdpSocket> ``` 2. 创建QUdpSocket对象:可以通过以下方法来创建一个QUdpSocket对象: ```c++ QUdpSocket *udpSocket = new QUdpSocket(this); ``` 在创建QUdpSocket对象时,可以通过指定父对象来自动管理对象的内存,避免内存泄漏。 3. 绑定端口号:在使用QUdpSocket接收UDP数据包时,需要将QUdpSocket对象绑定到一个端口号上,以便接收来自该端口的数据包。可以通过以下方法来绑定端口号: ```c++ udpSocket->bind(port); ``` 其中,port为要绑定的端口号。 4. 发送UDP数据包:可以通过以下方法来发送UDP数据包: ```c++ udpSocket->writeDatagram(data, host, port); ``` 其中,data为要发送的数据,host为目标主机的IP地址,port为目标主机的端口号。 5. 接收UDP数据包:可以通过以下方式来接收UDP数据包: ```c++ QByteArray datagram; datagram.resize(udpSocket->pendingDatagramSize()); udpSocket->readDatagram(datagram.data(), datagram.size()); ``` 其中,datagram为接收到的数据包。 6. 关闭QUdpSocket对象:在使用完QUdpSocket对象后,应该及时关闭该对象以释放资源: ```c++ udpSocket->close(); ``` 以上就是使用QUdpSocket进行UDP网络编程的基本步骤。需要注意的是,UDP是无连接的协议,发送的数据包不保证一定能够到达目标主机,因此需要在应用程序中自行处理数据包的可靠性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值