|
|
#include "udpsocketworker.h"
|
|
|
|
|
|
#include "common.h"
|
|
|
|
|
|
UdpSocketWorker::UdpSocketWorker(const QHostAddress hostAddr, const int port, QObject *parent)
|
|
|
: QObject(parent)
|
|
|
, m_udpSocket(new QUdpSocket(this))
|
|
|
{
|
|
|
m_udpSocket->bind(hostAddr, port);
|
|
|
connect(m_udpSocket, &QUdpSocket::readyRead, this, &UdpSocketWorker::processPendingDatagrams);
|
|
|
}
|
|
|
|
|
|
UdpSocketWorker::~UdpSocketWorker()
|
|
|
{
|
|
|
m_udpSocket->close();
|
|
|
qDeleteAll(m_timers); // 清理所有动态创建的定时器
|
|
|
}
|
|
|
|
|
|
void UdpSocketWorker::sendData(const QByteArray &data, const QHostAddress &address, quint16 port)
|
|
|
{
|
|
|
m_udpSocket->writeDatagram(data, address, port);
|
|
|
}
|
|
|
|
|
|
void UdpSocketWorker::processPendingDatagrams()
|
|
|
{
|
|
|
while (m_udpSocket->hasPendingDatagrams())
|
|
|
{
|
|
|
QByteArray datagram;
|
|
|
datagram.resize(static_cast<int>(m_udpSocket->pendingDatagramSize()));
|
|
|
m_udpSocket->readDatagram(datagram.data(), datagram.size());
|
|
|
|
|
|
emit dataReceived(datagram);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
void UdpSocketWorker::startSending(const QString &id, const QByteArray &data, const QHostAddress &address, const quint16 port, int interval)
|
|
|
{
|
|
|
if (m_timers.contains(id))
|
|
|
{
|
|
|
stopSending(id); // 如果存在相同ID的定时器,先停止
|
|
|
}
|
|
|
|
|
|
QTimer *timer = new QTimer(this); // 创建新的定时器
|
|
|
m_timers[id] = timer;
|
|
|
m_dataToSend[id] = data;
|
|
|
m_targetAddress[id] = address;
|
|
|
|
|
|
connect(timer, &QTimer::timeout, this, [=]() {
|
|
|
sendData(m_dataToSend[id], m_targetAddress[id], port);
|
|
|
});
|
|
|
|
|
|
timer->start(interval);
|
|
|
}
|
|
|
|
|
|
void UdpSocketWorker::stopSending(const QString &id)
|
|
|
{
|
|
|
if (m_timers.contains(id)) {
|
|
|
QTimer *timer = m_timers.take(id);
|
|
|
timer->stop();
|
|
|
timer->deleteLater(); // 删除定时器对象
|
|
|
m_dataToSend.remove(id);
|
|
|
m_targetAddress.remove(id);
|
|
|
}
|
|
|
}
|