多线程创建4个子线程,子线程tcp收数据,接收到的数据类型为泛型数据T,将收到的数据通过Qvetor<T>发送给主线程,其中T是自定义类型。主线程收数据,收到的数据放入QMap<QString,QVctor<T>>中,根据不同的QString和T类型分类数据,比较同一个Map中数据的一致性,思考一下,请用qt写一段代码,代码包含.h和.cpp。
时间: 2024-02-13 17:05:16 浏览: 66
QT多线程编程、主线程与子线程交互数据
5星 · 资源好评率100%
以下是我的实现,包括一个TCPClient类和一个主函数:
TCPClient.h
```cpp
#ifndef TCPCLIENT_H
#define TCPCLIENT_H
#include <QObject>
#include <QTcpSocket>
#include <QThread>
#include <QVector>
// 自定义类型
struct CustomData {
int id;
QString name;
};
// TCP客户端类
class TCPClient : public QObject
{
Q_OBJECT
public:
explicit TCPClient(QObject *parent = nullptr);
void start(const QString& host, quint16 port);
signals:
void dataReceived(const QString& key, const QVector<CustomData>& data);
private slots:
void readData();
private:
QTcpSocket m_socket;
};
#endif // TCPCLIENT_H
```
TCPClient.cpp
```cpp
#include "TCPClient.h"
TCPClient::TCPClient(QObject *parent) : QObject(parent)
{
connect(&m_socket, &QTcpSocket::readyRead, this, &TCPClient::readData);
}
// 启动客户端
void TCPClient::start(const QString& host, quint16 port)
{
m_socket.connectToHost(host, port);
if (!m_socket.waitForConnected()) {
qDebug() << "Error: " << m_socket.errorString();
return;
}
}
// 读取数据
void TCPClient::readData()
{
// 读取key和数据
QByteArray rawKey, rawData;
m_socket.read(2);
quint16 keySize = *(reinterpret_cast<const quint16*>(rawKey.data()));
rawKey.resize(keySize);
m_socket.read(rawKey);
m_socket.read(4);
quint32 dataSize = *(reinterpret_cast<const quint32*>(rawData.data()));
rawData.resize(dataSize);
m_socket.read(rawData);
// 解析数据
QString key = QString::fromUtf8(rawKey);
QVector<CustomData> data;
int pos = 0;
while (pos < dataSize) {
CustomData customData;
memcpy(&customData, rawData.data() + pos, sizeof(CustomData));
pos += sizeof(CustomData);
data.append(customData);
}
// 发送信号
emit dataReceived(key, data);
}
```
main.cpp
```cpp
#include <QCoreApplication>
#include <QMap>
#include <QVector>
#include <QDebug>
#include "TCPClient.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 创建TCP客户端
TCPClient client;
client.start("localhost", 12345);
// 数据统计
QMap<QString, QVector<CustomData>> dataMap;
QObject::connect(&client, &TCPClient::dataReceived, [&dataMap](const QString& key, const QVector<CustomData>& data){
// 添加数据
if (!data.isEmpty()) {
if (!dataMap.contains(key)) {
dataMap.insert(key, QVector<CustomData>());
}
dataMap[key].append(data);
}
// 比较数据
if (dataMap.contains("A") && dataMap.contains("B")) {
QVector<CustomData>& dataA = dataMap["A"];
QVector<CustomData>& dataB = dataMap["B"];
for (const CustomData& data1 : dataA) {
for (const CustomData& data2 : dataB) {
if (data1.id == data2.id && data1.name == data2.name) {
qDebug() << "Found matching data: " << data1.id << ", " << data1.name;
}
}
}
}
});
return a.exec();
}
```
阅读全文