-
Notifications
You must be signed in to change notification settings - Fork 11
/
sendthread.cc
67 lines (60 loc) · 1.81 KB
/
sendthread.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include "sendthread.hpp"
#include <QNetworkInterface>
#include <QUdpSocket>
struct SendThread::SendThreadPrivate
{
volatile bool runing = true;
const quint16 sendPort = 6000;
};
SendThread::SendThread(QObject *parent)
: QThread{parent}
, d_ptr(new SendThreadPrivate)
{}
SendThread::~SendThread()
{
onStop();
}
void SendThread::onStart()
{
d_ptr->runing = true;
if (isRunning()) {
return;
}
start();
}
void SendThread::onStop()
{
d_ptr->runing = false;
if (isRunning()) {
quit();
wait();
}
}
void SendThread::run()
{
QScopedPointer<QUdpSocket> sendUdpSocket(new QUdpSocket);
int loop = 3; // 发送多次
qInfo() << "Start Send-----------------";
while (d_ptr->runing && loop > 0) {
const QByteArray buf = "Hello " + QByteArray::number(loop);
QList<QNetworkInterface> interfaceList = QNetworkInterface::allInterfaces();
for (const QNetworkInterface &interface : std::as_const(interfaceList)) {
QList<QNetworkAddressEntry> entryList = interface.addressEntries();
for (const QNetworkAddressEntry &entry : std::as_const(entryList)) {
const QHostAddress broadcastAdress = entry.broadcast();
if (broadcastAdress == QHostAddress::Null
|| broadcastAdress == QHostAddress::LocalHost) {
continue;
}
sendUdpSocket->writeDatagram(buf, broadcastAdress, d_ptr->sendPort);
qInfo() << "Send To:" << broadcastAdress << buf;
sendUdpSocket->flush();
}
}
sendUdpSocket->writeDatagram(buf, QHostAddress::Broadcast, d_ptr->sendPort);
sendUdpSocket->flush();
QThread::msleep(100);
loop--;
}
qInfo() << "Stop Send-----------------";
}