2025-03-13 15:12:03 +08:00
|
|
|
#ifndef MYTCPCLIENT_H
|
|
|
|
#define MYTCPCLIENT_H
|
|
|
|
|
|
|
|
#include <QTcpSocket>
|
|
|
|
#include <QTimer>
|
|
|
|
#include <QObject>
|
2025-04-11 20:27:45 +08:00
|
|
|
#include "data_config.h"
|
2025-03-13 15:12:03 +08:00
|
|
|
|
|
|
|
class MyTcpClient : public QObject {
|
|
|
|
Q_OBJECT
|
|
|
|
|
|
|
|
public:
|
2025-03-20 14:38:14 +08:00
|
|
|
static MyTcpClient* instance();
|
2025-03-13 15:12:03 +08:00
|
|
|
explicit MyTcpClient(QObject *parent = nullptr);
|
|
|
|
~MyTcpClient();
|
|
|
|
|
|
|
|
void connectToServer(const QString &host, quint16 port);
|
|
|
|
int sendData(char* data,qint64 len);
|
|
|
|
void waitForRead();
|
|
|
|
void disconnectFromServer();
|
|
|
|
|
|
|
|
signals:
|
|
|
|
void connected();
|
|
|
|
void disconnected();
|
|
|
|
void dataReceived(const QByteArray &data);
|
|
|
|
void errorOccurred(const QString &errorMsg);
|
|
|
|
|
|
|
|
private slots:
|
|
|
|
void onConnected();
|
|
|
|
void onReadyRead();
|
|
|
|
void onDisconnected();
|
|
|
|
void onErrorOccurred(QAbstractSocket::SocketError socketError);
|
|
|
|
void onReconnect();
|
|
|
|
|
|
|
|
private:
|
|
|
|
QTcpSocket *socket;
|
|
|
|
QTimer reconnectTimer; // 自动重连定时器
|
|
|
|
QTimer heartbeatTimer; // 心跳包定时器
|
|
|
|
QString serverHost;
|
|
|
|
quint16 serverPort;
|
|
|
|
bool shouldReconnect; // 标记是否需要重连
|
2025-03-20 14:38:14 +08:00
|
|
|
static MyTcpClient* m_instance;
|
2025-04-11 20:27:45 +08:00
|
|
|
|
|
|
|
QByteArray m_buffer; // 存储当前正在接收的数据
|
|
|
|
bool m_waitingForHeader = true; // 是否在等待头部
|
2025-05-14 23:14:50 +08:00
|
|
|
|
|
|
|
uint8_t header[4];
|
|
|
|
int packge_len ;
|
2025-03-13 15:12:03 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
#endif // MYTCPCLIENT_H
|