QT通信基础—UDP

UDP客户端——UDP服务器
QT已封装好,使用里面的几个类可以进行简单的通信

服务器端代码

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(ui->pushButton,&QPushButton::clicked,this,&MainWindow::starBtnClicked);
    port=5555;
    isstart=false;
    udpSockedt=new QUdpSocket(this);
    timer=new QTimer(this);
    connect(timer,&QTimer::timeout,this,&MainWindow::timeout);
 //connect(timer,SIGNAL(QTimer::timeout()),this,SLOT(QTimer::timeout()));
}

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

void MainWindow::starBtnClicked()
{
    if(!isstart)
    {
        ui->pushButton->setText("停止");
        timer->start(1000);
        isstart=true;
    }else {
        ui->pushButton->setText("开始");
        isstart=false;
        timer->stop();
    }
}

void MainWindow::timeout()
{
    QString msg=ui->lineEdit->text();
    int length=0;
    if (msg=="")
    {
        qDebug() << "msg==""";
        return;
    }
    if ((length=udpSockedt->writeDatagram(msg.toLatin1(),msg.length(),QHostAddress::Broadcast,port))!=msg.length())
{return;}
}

加上需要头文件以及QT+=network 将QT的网络模块添加到项目中

UDP客户端的代码

udpClient::udpClient(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::udpClient)
{
    ui->setupUi(this);
    setWindowTitle("UDP Client");
    connect(ui->closeBtn,&QPushButton::clicked,this,&udpClient::CloseBtnClicked);
    port=5555;
    //isstart=false;
    udpSocket=new QUdpSocket(this);
    //timer=new QTimer(this);
    connect(udpSocket,&QIODevice::readyRead,this,&udpClient::dataReceived);//readyRead信号是由QUdpsocket继承过来的
    bool result=udpSocket->bind(port);
    if (!result)
    {
        QMessageBox::information(this,"error","udp socket create error");
        return;
    }

}

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

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

void udpClient::dataReceived()
{
    while(udpSocket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;
        // 读取数据报
        udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
        // 输出接收到的数据
        qDebug() << "Received from" << sender.toString() << ":" << senderPort << "data:" << datagram;
        ui->textEdit->insertPlainText(datagram.data());
         ui->textEdit->insertPlainText(sender.toString());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值