QT,利用UDP接收数据包,每当收到100个数据包建立一个文件存储,文件名以系统时间命名
这是自己参考网上UDP接收数据包写的代码,发现只能在第一个文件中存进去数据,第二个文件可以建立成功,但写不进去数据,请大神们帮忙看看,或者帮忙换一个思路,谢谢各位。
下面是进程的 .h文件和 .cpp文件。
#ifndef STORE_H
#define STORE_H
#include <QThread>
#include <QtCore>
#include <QObject>
#include <QMutex>
#include <iostream>
#include <QtNetwork>
class QUdpSocket;
class store : public QThread
{
public:
store();
private slots:
void run();
void processPendingDatagram();
private:
QMutex m_lock;
QUdpSocket *receiver;
QFile f();
};
#endif // STORE_H
#include "store.h"
#include <iostream>
store::store()
{
//创建一个QUdpSocket类对象,该类提供了Udp的许多相关操作
receiver = new QUdpSocket(this);
int port = 45454;//设置UDP的端口号参数,指定在此端口上监听数据
//此处的bind是个重载函数,连接本机的port端口,采用ShareAddress模式(即允许其它的服务连接到相同的地址和端口,特别是
//用在多客户端监听同一个服务器端口等时特别有效),和ReuseAddressHint模式(重新连接服务器)
int receive = receiver->bind(QHostAddress("192.168.0.3"),port);
if(receive != -1)
{qDebug() << "UDP Connected Succeed ! ";}
else
{qDebug() << "UDP Connected Faild ! ";}
}
void store::run()
{
//获得系统时间并输出
QString min = QDateTime::currentDateTime().toString("yyyyMMddhhmmss");
//打开文本 以时间命名文件名字
QString fileName = "C:\\" + min + ".txt";
QFile f(fileName);
if(!f.open( QIODevice::WriteOnly | QIODevice::Text))
return;
int i=1;
while(1)
{
while(receiver->hasPendingDatagrams()) //拥有等待的数据报
{
QByteArray datagram; //拥于存放接收的数据报
datagram.resize(receiver->pendingDatagramSize());
receiver->readDatagram(datagram.data(),datagram.size());
QString HexData = datagram.toHex();
if(i % 100 == 0)
{
f.close();
//获得系统时间并输出
QString min = QDateTime::currentDateTime().toString("yyyyMMddhhmmss");
qDebug() << "write again !";
QString fileName = "C:\\" + min + ".txt";
QFile f(fileName);
if(!f.open( QIODevice::WriteOnly | QIODevice::Text))
return;
f.flush();
}
QTextStream put(&f);
put << HexData ;
i = i + 1;
}
}
}
/***********GNSS数据处理***********/
void store::processPendingDatagram()
{
}