50 lines
1.3 KiB
C++
50 lines
1.3 KiB
C++
#ifndef MYTCPCLIENT_H
|
|
#define MYTCPCLIENT_H
|
|
|
|
#include <QTcpSocket>
|
|
#include <QTimer>
|
|
#include <QObject>
|
|
#include "data_config.h"
|
|
|
|
class MyTcpClient : public QObject {
|
|
Q_OBJECT
|
|
|
|
public:
|
|
static MyTcpClient* instance();
|
|
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; // 标记是否需要重连
|
|
static MyTcpClient* m_instance;
|
|
|
|
QByteArray m_buffer; // 存储当前正在接收的数据
|
|
bool m_waitingForHeader = true; // 是否在等待头部
|
|
PackageHead m_currentHead; // 当前包的头部信息
|
|
};
|
|
|
|
#endif // MYTCPCLIENT_H
|