#include "client.h" #include #include #include Client::Client(QObject *parent) : QObject(parent) { socket = new QTcpSocket(this); connect(socket, &QTcpSocket::errorOccurred, this, &Client::errorOccurred); connect(socket, &QTcpSocket::connected, this, &Client::connected); connect(socket, &QTcpSocket::disconnected, this, &Client::disconnected); timer = new QTimer(this); timer->setSingleShot(true); connect(timer, &QTimer::timeout, this, &Client::timeout); } bool Client::connectToHost(const QString& host) { this->host = host; retryConnect(); return true; } bool Client::writeData(const QByteArray& data) { if(socket->state() != QAbstractSocket::ConnectedState) { return false; } std::uint32_t size = data.size(); socket->write((char*)&size, sizeof(std::uint32_t)); socket->write(data); return socket->waitForBytesWritten(100); // wait at most 100ms } void Client::errorOccurred(QAbstractSocket::SocketError socketError) { if(socketError == QAbstractSocket::NetworkError || socketError == QAbstractSocket::ConnectionRefusedError) { if(retries > 0) { timer->setInterval(interval * 1000); retries--; } else { timer->setInterval(interval_long * 1000); } timer->start(); } } void Client::connected() { emit isConnected(); } void Client::disconnected() { emit isDisconnected(); retryConnect(); } void Client::timeout() { retryConnect(); } void Client::retryConnect() { socket->connectToHost(host, 1024); }