QT upd测试
本次测试将服务器和客户端写在了一个工程下,代码如下
widget.h
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include<QUdpSocket>
#include<QTimer>QT_BEGIN_NAMESPACE
namespace Ui {
class Widget;
}
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();private slots:void on_pushButton_clicked();void dataReceived();void on_pushButton_2_clicked();void timeoutslot();private:Ui::Widget *ui;public:int m_iport;bool m_bisstarted;QUdpSocket *udpSocket_server;QUdpSocket *udpSocket_client;QTimer *timer;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);m_iport = 5555;udpSocket_server = new QUdpSocket(this);udpSocket_client = new QUdpSocket(this);udpSocket_client->bind(m_iport);timer = new QTimer(this);connect(timer , SIGNAL(timeout()) , this , SLOT(timeoutslot()));connect(udpSocket_client , SIGNAL(readyRead()) , this , SLOT(dataReceived()));this->setWindowTitle("updtest");}Widget::~Widget()
{delete ui;
}void Widget::on_pushButton_clicked()
{timer->start(500);
}void Widget::timeoutslot()
{QString msg = ui->lineEdit_send->text();if(msg.size()==0){return;}//转成utf8 避免中文乱码udpSocket_server->writeDatagram(msg.toUtf8 ().data(), msg.toUtf8().size() , QHostAddress::Broadcast , m_iport);}void Widget::on_pushButton_2_clicked()
{close();
}void Widget::dataReceived()
{while(udpSocket_client->hasPendingDatagrams()){QByteArray datagram;datagram.resize(udpSocket_client->pendingDatagramSize());udpSocket_client->readDatagram(datagram.data() , datagram.size());QString msg = datagram.data();ui->textEdit->insertPlainText(msg);}
}
运行结果如下: