方法:建立UDP广播,然后将数据存放在内存,另一个线程进行数据的发送;
具体代码如下
头文件如下所示:
#pragma once
#include <QThread>
#include <UDPSendData.h>
#include <QMutex>
class CUDPSendThread : public QThread
{
Q_OBJECT
public:
CUDPSendThread(QObject* parent = NULL);
~CUDPSendThread(void);
void appendData(MemoryMsg& memory);
void run();
private:
QList<MemoryMsg> mUDPData;
QMutex m_Mutex;
QMutex m_InterMutex;
bool mIsStop;
CUDPSendData* mUdpSend;
};
源代码如下所示:
#include "UDPSendThread.h"
#include "chostaddress.h"
CUDPSendThread::CUDPSendThread(QObject* parent):QThread(parent)
{
mIsStop = false;
mUdpSend = new CUDPSendData();
CHostAddress nHost;
QString nIP = nHost.getHostAddress();
quint16 nPort =nHost.getPort();
if (nIP != "")
{
mUdpSend->setHostAddress(nIP,nPort);
}
else
{
mUdpSend->setHostAddress(QString("224.154.11.202"),5451);
}
mUdpSend->initSocket();
}
CUDPSendThread::~CUDPSendThread(void)
{
}
void CUDPSendThread::appendData(MemoryMsg& memory)
{
m_Mutex.lock();
mUDPData.append(memory);
m_Mutex.unlock();
}
void CUDPSendThread::run()
{
while(!mIsStop)
{
QList<MemoryMsg> nUDPData;
m_Mutex.lock();
nUDPData = mUDPData;
mUDPData.clear();
m_Mutex.unlock();
m_InterMutex.unlock();
if (nUDPData.size() > 0)
{
for (int i = 0; i < nUDPData.size(); i++)
{
mUdpSend->setData(nUDPData[i]);
}
}
if(nUDPData.size() < 1)
{
msleep(15);
}
}
}
配置文件如下
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<ipconfig>
<node hostaddress="127.54.11.22" port="1234"></node>
</ipconfig>
使用方法:
CUDPSendThread *sendThread = new CUDPSendThread();
sendThread->start();
然后组织一个MemoryMsg结构体,这个可自行定义;
然后使用sendThread->appendData(你的结构体);
这样就实现了数据的UDP广播