实现代码如下:
- #include "UdpBroadcast.h"
- #include "ui_UdpBroadcast.h"
- UdpBroadcast::UdpBroadcast(QWidget *parent) :
- QMainWindow(parent),
- ui(new Ui::UdpBroadcast)
- {
- ui->setupUi(this);
- ui->spinBox_time->setValue(1);
- QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));
- // QTextCodec::setCodecForLocale(QTextCodec::codecForName("utf-8"));
- // QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GBK"));
- this->connect(ui->pushButton_BroadCast,SIGNAL(clicked()),this,SLOT(slotBroadcast()));
- this->connect(ui->pushButton_connt,SIGNAL(clicked()),this,SLOT(slotClientConnect()));
- this->connect(ui->tabWidget,SIGNAL(currentChanged(int)),this,SLOT(slotTabChange(int)));
- }
- UdpBroadcast::~UdpBroadcast()
- {
- delete ui;
- }
- void UdpBroadcast::slotTabChange(int i)
- {
- if(i==0)
- {
- this->setWindowTitle(tr("服务端"));
- }
- else if(i==1)
- {
- this->setWindowTitle(tr("客户端"));
- }
- }
- void UdpBroadcast::slotBroadcast()
- {
- m_Server_udp = new QUdpSocket(this);
- m_timer = new QTimer(this);
- this->connect(m_timer,SIGNAL(timeout()),this,SLOT(soltTiming()));
- m_timer->start(ui->spinBox_time->text().toInt()*1000); //定时器
- }
- void UdpBroadcast::soltTiming()
- {
- QString qStrMesg = ui->lineEdit_Mesg->text();
- qDebug()<<endl;
- qDebug()<<qStrMesg;
- if(qStrMesg == "")
- {
- return;
- }
- int length;
- //发送
- if((length = m_Server_udp->writeDatagram(qStrMesg.toUtf8(),qStrMesg.toUtf8().length(),QHostAddress::Broadcast,55555)))
- {
- return;
- }
- }
- void UdpBroadcast::slotClientConnect()
- {
- ui->textEdit_Mesg->clear();
- m_Client_udp = new QUdpSocket(this);
- m_Client_udp->bind(55555);
- this->connect(m_Client_udp,SIGNAL(readyRead()),this,SLOT(slotClientReadMesg()));
- }
- void UdpBroadcast::slotClientReadMesg()
- {
- while(m_Client_udp->hasPendingDatagrams()) //是否有数据报过来
- {
- QByteArray qdata;
- qdata.resize(m_Client_udp->pendingDatagramSize()); //数据报大小
- m_Client_udp->readDatagram(qdata.data(),qdata.size()); //读取
- QString ss;
- ss = QString::fromUtf8(qdata); //中文
- ui->textEdit_Mesg->append(ss);
- }
- }
