第10章:UdpClient

1,UDP客户端

2,源码:

#include "mainwindow.h"
#include "ui_mainwindow.h"

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

    port        = 7755;
    isStarted   = false;
    udpSocket   = new QUdpSocket(this);

    timer       = new QTimer(this);
    this->setWindowTitle(tr("UDP Client"));
}

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



void MainWindow::on_pushButton_clicked()
{
    if (!isStarted)
    {
        ui->pushButton->setText(tr("Stop"));
        isStarted = true;

        udpSocket->bind(QHostAddress::LocalHost, port);
        connect(udpSocket, SIGNAL(readyRead()), this, SLOT(Udp_ReceiveData()));

        timer->start(1000);
        connect(timer, SIGNAL(timeout()), this, SLOT(Udp_SendData()));
    }
    else
    {
        ui->pushButton->setText(tr("Start"));
        isStarted = false;

        timer->stop();
        disconnect(timer, SIGNAL(timeout()), this, SLOT(Udp_SendData()));

        disconnect(udpSocket, SIGNAL(readyRead()), this, SLOT(Udp_ReceiveData()));
        udpSocket->close();
    }
}



void MainWindow::Udp_ReceiveData()
{
    QHostAddress sender;
    quint16      senderport;
    QByteArray   datagram;
    qint64       length;

    while(udpSocket->hasPendingDatagrams())
    {
        datagram.resize(udpSocket->pendingDatagramSize());
        length = udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderport);
        if (length > 0)
        {
            ui->textEdit->insertPlainText(tr("Rx: "));
            ui->textEdit->insertPlainText(QString(datagram) + " Sender IP: "+ sender.toString() + ";Port: " + QString::number(senderport)  +"\n");
            ui->textEdit->moveCursor(QTextCursor::End);
        }
    }
}


void MainWindow::Udp_SendData()
{
    QHostAddress sender;
    sender.setAddress(QString("127.0.0.1"));
    quint16 senderport = 5555;

    QString text = "I am Client";
    QByteArray datagram = text.toLocal8Bit();
    udpSocket->writeDatagram(datagram.data(), datagram.size(), sender, senderport);
}


void MainWindow::on_ClearButton_clicked()
{
    ui->textEdit->clear();
}

3,效果:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值