1.使用QUdpSocket之前需要在项目的xxx.pro文件中加入
QT += network
2. udp 广播发送端代码
widget.hwi
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QFile>
#include <QThread>
#include <QMessageBox>
#include <QUdpSocket>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
void on_readyRead();
private:
Ui::Widget *ui;
QString fileName;
QString serverName;
QString readServerName();
QUdpSocket *m_udpSocket = nullptr;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QTextStream>
#include <QTimer>
#pragma execution_character_set("utf-8")
void delay(int mSec)//ms
{
QEventLoop loop;
QTimer::singleShot(mSec, &loop, SLOT(quit()));
loop.exec();
}
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
m_udpSocket = new QUdpSocket(this);
connect(m_udpSocket,&QUdpSocket::readyRead,this,&Widget::on_readyRead);
// qint16 port = 11021;
// if(m_udpSocket->bind(port))
// {
// ui->plainTextEdit->appendPlainText("**已成功绑定");
// ui->plainTextEdit->appendPlainText("**绑定端口: "+QString::number(m_udpSocket->localPort()));
// }
// else
// {
// ui->plainTextEdit->appendPlainText("**绑定失败");
// }
}
Widget::~Widget()
{
m_udpSocket->abort();
delete ui;
}
//打开
void Widget::on_pushButton_clicked()
{
quint16 dstPort = 11022;
QString msg = QString("start=1,slave=%1").arg(ui->spinBox->value());
//发出数据报
m_udpSocket->writeDatagram(msg.toLocal8Bit(), msg.length(), QHostAddress::Broadcast, dstPort);
ui->plainTextEdit->appendPlainText("[Broadcast] "+msg);
ui->pushButton->setEnabled(false);
delay(3000);
ui->pushButton_2->setEnabled(true);
}
//关闭
void Widget::on_pushButton_2_clicked()
{
quint16 dstPort = 11022;
QString msg = QString("start=0,slave=%1").arg(ui->spinBox->value());
//发出数据报
m_udpSocket->writeDatagram(msg.toLocal8Bit(), msg.length(), QHostAddress::Broadcast, dstPort);
ui->plainTextEdit->appendPlainText("[Broadcast] "+msg);
ui->pushButton_2->setEnabled(false);
delay(3000);
ui->pushButton->setEnabled(true);
}
void Widget::on_readyRead()
{
}
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
3.udp接收端代码
udpclient.h
#ifndef UDPCLIENT_H
#define UDPCLIENT_H
#include <QObject>
#include <QUdpSocket>
class UdpClient: public QObject
{
Q_OBJECT
private:
int port;
QUdpSocket *udpSocket;
public:
UdpClient(QObject *parent = 0);
private slots:
void dataReceived();
};
#endif // UDPCLIENT_H
udpclient.cpp
#include "udpclient.h"
#include <QMessageBox>
#include <QUdpSocket>
#include <QProcess>
#include <QFile>
#include <QDir>
void closeSlaveProcess()
{
QStringList params;
params<<"/c"<<"taskkill"<<"-f"<<"-im"<<"slave1.exe";
QProcess process;
process.start("cmd.exe",params);
process.waitForFinished();
process.close();
}
void openSlaveProcess()
{
qDebug()<<"start open";
QProcess process;
process.startDetached("C:/Services/slave1_ds2/slave1.exe", QStringList()<<"");
}
UdpClient::UdpClient(QObject *parent)
: QObject(parent)
{
QDir dir;
if(!dir.exists("C:/services/controlSlave/logs"))
dir.mkpath("C:/services/controlSlave/logs");
port = 11022;
udpSocket = new QUdpSocket(this);
bool result = udpSocket->bind(port);
if(!result) {
qDebug()<<"fail";
return ;
}
connect(udpSocket, SIGNAL(readyRead()),
this, SLOT(dataReceived()));
}
void UdpClient::dataReceived()
{
while(udpSocket->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(udpSocket->pendingDatagramSize());
udpSocket->readDatagram(datagram.data(), datagram.size());
QString data = datagram.data();
qDebug()<<data;
if(data.contains("start") && data.contains("slave"))
{
QStringList con = data.split(",");
if(con.count()>=2)
{
QString start = con.at(0);
if(start.replace("start=","").toInt() == 0)
closeSlaveProcess();
else if(start.replace("start=","").toInt() == 1)
{
QFile file("C:/Services/Maxprocesses.txt");
if(file.open(QIODevice::WriteOnly | QIODevice::Truncate))
{
QString num = con.at(1);
file.write(num.replace("slave=","").toLatin1());
file.close();
}
openSlaveProcess();
}
}
}
}
}
main.cpp
#include <QApplication>
#include <udpclient.h>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
UdpClient *client = new UdpClient;
return a.exec();
}