Qt学习(六):UDP通信

12 篇文章 2 订阅

知识点

https://github.com/taw19960426/Qt_study/tree/main/QUdpSocket

结果演示

在这里插入图片描述

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QHostAddress>

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

    setWindowTitle("服务端port:8888");

    udpSocket=new QUdpSocket(this);

    //绑定
    //udpSocket->bind(8888);
    udpSocket->bind(QHostAddress::AnyIPv4, 8888);

    //加入某个组播
    //组播地址是D类地址
    udpSocket->joinMulticastGroup( QHostAddress("224.0.0.2") );
    //udpSocket->leaveMulticastGroup(); //退出组播

    //当对方成功发送数据过来
    //自动触发 readyRead()
    connect(udpSocket,&QUdpSocket::readyRead,this,&Widget::delUdp);
}

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

void Widget::delUdp(){
    //读取对方发送的内容
    char buf[1024]={0};
    QHostAddress ip;//对方地址
    quint16 port;//对方端口

    qint64 ans=udpSocket->readDatagram(buf,sizeof(buf),&ip,&port);
    //读到了
    if(ans>0){
        //格式化 [192.68.2.2:8888]aaaa
        QString str=QString("[%1:%2] %3").arg(ip.toString()).arg(port).arg(buf);

        //给编辑区设置内容
        ui->textEdit->setText(str);
    }
}

//发送按钮
void Widget::on_buttonSend_clicked()
{
    //先获取对方的IP和端口
    QString ip=ui->lineEditIP->text();
    quint16 port=ui->lineEditPort->text().toInt();

    //获取编辑区内容
    QString str=ui->textEdit->toPlainText();

    //给指定的IP发送数据
    udpSocket->writeDatagram(str.toUtf8(),QHostAddress(ip),port);
}

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QUdpSocket>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

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

private slots:
    void on_buttonSend_clicked();

private:
    Ui::Widget *ui;
    QUdpSocket *udpSocket;

    //定义处理的槽函数
    void delUdp();
};

#endif // WIDGET_H

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

唐维康

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

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

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

打赏作者

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

抵扣说明:

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

余额充值