看了相关资料,根据上一篇tcp的思路,写了下面这个程序,有点像傻子哈哈哈.先上代码:

#include "udp1.h"
#include <QVBoxLayout>
#include <QTime>

udp1::udp1(QWidget *parent) : QWidget(parent)
{
    browser = new QTextBrowser;
    browser->setReadOnly(true);
    edit = new QLineEdit;
    sendButton = new QPushButton("send");
    QVBoxLayout *layout = new QVBoxLayout;

    layout->addWidget(browser);
    layout->addWidget(edit);
    layout->addWidget(sendButton);

    this->setLayout(layout);   //布局


    socked = new QUdpSocket;   //建立udp
    socked->bind(10001);   //绑定端口

    connect(socked, SIGNAL(readyRead()), this, SLOT(slotreadytoread()));    //准备读取
    connect(sendButton, SIGNAL(clicked(bool)), this, SLOT(slotsend()));   //单击按钮
    connect(edit, SIGNAL(returnPressed()), sendButton, SLOT(click()));  //按下回车
    this->setWindowTitle("I'm A");

}

void udp1::slotreadytoread()
{
    while(socked->hasPendingDatagrams())
    {
        quint32 dataSize = socked->pendingDatagramSize();
        //获取大小
        QByteArray buf(dataSize, 0);
        //开辟空间
        socked->readDatagram(buf.data(), buf.size());
         //读入数据
        browser->append(tr("B:%1").arg(QTime::currentTime().toString()));
        browser->append(buf.data());
        //在browser附加数据
    }
}

void udp1::slotsend()
{
    QString str = edit->text();
    if(str.isEmpty())  //长度为0不发送
    {
        return;
    }
    this->browser->append(tr("A:%1\n%2").arg(QTime::currentTime().toString()).arg(this->edit->text()));  //附加
    socked->writeDatagram(str.toUtf8(), QHostAddress("127.0.0.1"), 10002);   //发送报文到ip和端口
    this->edit->clear(); //清除edit
}

由于两个类是一样的,除了名字不同,就只贴一个了.

贴图
udp.png
相关的东西注释也写得差不多了,其实就是懒哈哈,睡觉咯~

Last modification:June 30, 2019
If you think my article is useful to you, please feel free to appreciate