92 lines
2.7 KiB
C++
92 lines
2.7 KiB
C++
#include "MyTcpClient.h"
|
|
#include <QDebug>
|
|
|
|
MyTcpClient::MyTcpClient(QObject *parent) : QObject(parent), shouldReconnect(true) {
|
|
socket = new QTcpSocket(this);
|
|
|
|
connect(socket, &QTcpSocket::connected, this, &MyTcpClient::onConnected);
|
|
connect(socket, &QTcpSocket::readyRead, this, &MyTcpClient::onReadyRead);
|
|
connect(socket, &QTcpSocket::disconnected, this, &MyTcpClient::onDisconnected);
|
|
//connect(socket, &QTcpSocket::errorOccurred, this, &MyTcpClient::onErrorOccurred);
|
|
|
|
// 连接失败后,定时尝试重连
|
|
connect(&reconnectTimer, &QTimer::timeout, this, &MyTcpClient::onReconnect);
|
|
reconnectTimer.setInterval(5000); // 5秒重连一次
|
|
}
|
|
|
|
MyTcpClient::~MyTcpClient() {
|
|
shouldReconnect = false;
|
|
if (socket) {
|
|
socket->disconnectFromHost();
|
|
socket->deleteLater();
|
|
}
|
|
}
|
|
|
|
void MyTcpClient::connectToServer(const QString &host, quint16 port) {
|
|
serverHost = host;
|
|
serverPort = port;
|
|
if (socket->state() == QAbstractSocket::ConnectedState) {
|
|
qDebug() << "Already connected!";
|
|
return;
|
|
}
|
|
qDebug() << "Connecting to" << host << ":" << port;
|
|
socket->connectToHost(host, port);
|
|
if (!socket->waitForConnected()) {
|
|
qDebug() << "Connection failed!";
|
|
return;
|
|
}
|
|
}
|
|
|
|
int MyTcpClient::sendData(char*data,qint64 len) {
|
|
|
|
qint64 bytesWritten = socket->write(data, len);
|
|
socket->waitForBytesWritten();
|
|
return bytesWritten;
|
|
}
|
|
void MyTcpClient::waitForRead() {
|
|
socket->waitForReadyRead();
|
|
}
|
|
void MyTcpClient::disconnectFromServer() {
|
|
shouldReconnect = false; // 停止自动重连
|
|
reconnectTimer.stop();
|
|
heartbeatTimer.stop();
|
|
socket->disconnectFromHost();
|
|
}
|
|
|
|
void MyTcpClient::onConnected() {
|
|
qDebug() << "Connected to server!";
|
|
emit connected();
|
|
|
|
reconnectTimer.stop(); // 连接成功,停止自动重连
|
|
heartbeatTimer.start(); // 开始发送心跳包
|
|
}
|
|
|
|
void MyTcpClient::onReadyRead() {
|
|
QByteArray data = socket->readAll();
|
|
emit dataReceived(data);
|
|
}
|
|
|
|
void MyTcpClient::onDisconnected() {
|
|
qDebug() << "Disconnected from server!";
|
|
emit disconnected();
|
|
|
|
if (shouldReconnect) {
|
|
qDebug() << "Attempting to reconnect in 5 seconds...";
|
|
reconnectTimer.start(); // 触发自动重连
|
|
heartbeatTimer.stop(); // 断开后停止心跳
|
|
}
|
|
}
|
|
|
|
void MyTcpClient::onErrorOccurred(QAbstractSocket::SocketError socketError) {
|
|
Q_UNUSED(socketError)
|
|
qDebug() << "Socket error:" << socket->errorString();
|
|
emit errorOccurred(socket->errorString());
|
|
}
|
|
|
|
void MyTcpClient::onReconnect() {
|
|
if (socket->state() == QAbstractSocket::UnconnectedState) {
|
|
qDebug() << "Reconnecting to" << serverHost << ":" << serverPort;
|
|
socket->connectToHost(serverHost, serverPort);
|
|
}
|
|
}
|