-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathreceivethread.cc
74 lines (66 loc) · 1.9 KB
/
receivethread.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
68
69
70
71
72
73
74
#include "receivethread.hpp"
#include <QCoreApplication>
#include <QNetworkDatagram>
#include <QUdpSocket>
struct ReceiveThread::ReceiveThreadPrivate
{
const quint16 recvPort = 6000;
volatile bool runing = true;
};
ReceiveThread::ReceiveThread(QObject *parent)
: QThread{parent}
, d_ptr(new ReceiveThreadPrivate)
{}
ReceiveThread::~ReceiveThread()
{
onStop();
}
void ReceiveThread::onStart()
{
d_ptr->runing = true;
if (isRunning()) {
return;
}
start();
}
void ReceiveThread::onStop()
{
d_ptr->runing = false;
if (isRunning()) {
quit();
wait();
}
}
void ReceiveThread::run()
{
qInfo() << "Start Receive-----------------";
QScopedPointer<QUdpSocket> recvUdpSocket(new QUdpSocket);
// The recvUdpSocket.data() must no buffer data to read before bind, otherwise the readyRead signal will not be emitted.
// connect(recvUdpSocket.data(),
// &QUdpSocket::readyRead,
// this,
// &UdpReceiveThread::onReadyRead,
// Qt::DirectConnection);
auto bind = recvUdpSocket->bind(QHostAddress::Any, d_ptr->recvPort, QUdpSocket::ShareAddress);
if (bind) {
qInfo() << "bind success";
} else {
qInfo() << "bind failed";
return;
}
while (d_ptr->runing) {
recvUdpSocket->waitForReadyRead(100);
while (d_ptr->runing && recvUdpSocket->hasPendingDatagrams()) {
QNetworkDatagram datagram = recvUdpSocket->receiveDatagram();
processTheDatagram(datagram);
}
qApp->processEvents();
}
qInfo() << "Stop Receive-----------------";
}
void ReceiveThread::processTheDatagram(const QNetworkDatagram &datagram)
{
qInfo() << "Receive From:" << datagram.senderAddress().toString() << datagram.senderPort()
<< "To:" << datagram.destinationAddress() << datagram.destinationPort()
<< datagram.data();
}