Qt-利用QUdpSocket实现UDP点对点通信处理
相关资料:
https://download.csdn.net/download/zhujianqiangqq/47467208 代码包下载
udpsend.cpp主函数
1 #include "mainwindow.h" 2 #include "ui_mainwindow.h" 3 #include4 #include 5 #include 6 #include 7 8 const quint16 PORT = 2333; 9 10 MainWindow::MainWindow(QWidget *parent) 11 : QMainWindow(parent) 12 , ui(new Ui::MainWindow) 13 { 14 ui->setupUi(this); 15 16 m_pTimer = new QTimer(this); 17 m_pTimer->setSingleShot(false); 18 m_pTimer->start(1000); 19 connect(m_pTimer, &QTimer::timeout, this, &MainWindow::on_Timer); 20 } 21 22 MainWindow::~MainWindow() 23 { 24 delete ui; 25 } 26 27 void MainWindow::on_pushButton_clicked() 28 { 29 // 初始化UDP对象 30 QUdpSocket oUDPSend; 31 // 发送信息 32 QDateTime sysDateTime; 33 QByteArray msg = (sysDateTime.currentDateTime().toString("yyyy-MM-dd hh:mm:ss")+" \n").toLatin1(); 34 oUDPSend.writeDatagram(msg, QHostAddress("10.0.1.45"), PORT);// 需要先帮定127.0.0.1或10.0.1.45,都是本机IP 35 // 输出信息(提示用,没有实际作用) 36 ui->textEdit->insertPlainText(QStringLiteral("1")); 37 } 38 39 void MainWindow::on_Timer() 40 { 41 on_pushButton_clicked(); 42 }
udpReceiver.cpp主函数
1 #include "mainwindow.h" 2 #include "ui_mainwindow.h" 3 4 MainWindow::MainWindow(QWidget *parent) 5 : QMainWindow(parent) 6 , ui(new Ui::MainWindow) 7 { 8 ui->setupUi(this); 9 10 m_pUDPReceiver = new QUdpSocket; 11 m_pUDPReceiver->bind(QHostAddress("10.0.1.45"), PORT);// 第一步:需要先帮定127.0.0.1或10.0.1.45,都是本机IP 12 connect(m_pUDPReceiver, SIGNAL(readyRead()), this, SLOT(receive()));//第二步:帮定读取事件 13 } 14 15 MainWindow::~MainWindow() 16 { 17 delete ui; 18 delete m_pUDPReceiver; 19 } 20 21 void MainWindow::receive() 22 { 23 QByteArray ba; 24 QString ss; 25 while(m_pUDPReceiver->hasPendingDatagrams()) 26 { 27 ba.resize(m_pUDPReceiver->pendingDatagramSize()); 28 m_pUDPReceiver->readDatagram(ba.data(), ba.size()); 29 ss = QString::fromUtf8(ba.data()); 30 ui->textEdit->insertPlainText(ss); 31 } 32 }