Qt网络编程基础——UDP简易通讯

UDP通信流程与Qt实现
本文详细介绍了UDP通信的基本流程,通过Qt库实现了一个简单的UDP服务器。代码展示了如何使用QUdpSocket进行数据发送与接收,包括初始化通信套接字、绑定端口、发送数据以及接收并处理数据的过程。

首先展示UDP通信中的流程:

一、具体代码展示

1、两端通信只需要通信两端同时使用<QUdpSocket>内提供的socket进行通信即可,无服务器和客户端之分

头文件:

#ifndef UDPSERVER_H
#define UDPSERVER_H

#include <QWidget>
#include <QUdpSocket>

namespace Ui {
class UdpServer;
}

class UdpServer : public QWidget
{
    Q_OBJECT

public:
    explicit UdpServer(QWidget *parent = 0);
    ~UdpServer();

private slots:

    void on_pb_send_clicked();

    void on_pushButton_3_clicked();

    void dealSomething();

private:
    Ui::UdpServer *ui;
    QUdpSocket *udpSocket;
};

#endif // UDPSERVER_H

具体实现:

#include "udpserver.h"
#include "ui_udpserver.h"

#include <QString>
#include <QByteArray>

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

    //显示为通信套接字开辟空间,并指定父对象
    udpSocket = new QUdpSocket(this);

    setWindowTitle("服务器端口: 8888");

    udpSocket->bind(8888);

    //当对方成功把数据发送过来
    connect(udpSocket, SIGNAL(readyRead()),
            this, SLOT(dealSomething()));

}

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

void UdpServer::on_pb_send_clicked()
{
    QString str = ui->te_write->toPlainText();
    QString ip = ui->le_ip->text();
    quint16 port = ui->le_port->text().toInt();
    udpSocket->writeDatagram(str.toUtf8(), QHostAddress(ip), port);
}

void UdpServer::on_pushButton_3_clicked()
{

}


void UdpServer::dealSomething()
{
    //接受信息
    char buff[1024] = {0};
    QHostAddress add;
    quint16 port;
    qint64 len = udpSocket->readDatagram(buff, sizeof(buff),
                     &add, &port);
    if(len > 0)
    {
        QString str = QString("[%1:%2] %3").arg(add.toString()).arg(port).arg(buff);

        ui->te_read->setText(str);
    }
}

二、效果展示:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Star星屹程序设计

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值