1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
#include "blockingsocket.h"
#include "common/global.h"
#include "common/threadwitheventloop.h"
#include "common/private/blockingsocketprivate.h"
#include <QMutexLocker>
BlockingSocket::BlockingSocket(QObject* parent) :
QObject(parent)
{
socketThread = new ThreadWithEventLoop;
socket = new BlockingSocketPrivate;
socket->moveToThread(socketThread);
connect(socketThread, &QThread::finished, socket, &QObject::deleteLater);
connect(socketThread, &QThread::finished, socketThread, &QObject::deleteLater);
connect(this, SIGNAL(callForSend(QByteArray,bool&)), socket, SLOT(handleSendCall(QByteArray,bool&)), Qt::BlockingQueuedConnection);
connect(this, SIGNAL(callForRead(qint64,int,QByteArray&,bool&)), socket, SLOT(handleReadCall(qint64,int,QByteArray&,bool&)), Qt::BlockingQueuedConnection);
connect(this, SIGNAL(callForConnect(QString,int,bool&)), socket, SLOT(handleConnectCall(QString,int,bool&)), Qt::BlockingQueuedConnection);
connect(this, SIGNAL(callForDisconnect()), socket, SLOT(handleDisconnectCall()), Qt::BlockingQueuedConnection);
connect(this, SIGNAL(callForIsConnected(bool&)), socket, SLOT(handleIsConnectedCall(bool&)), Qt::BlockingQueuedConnection);
connect(socket, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
socketThread->start();
}
BlockingSocket::~BlockingSocket()
{
QMutexLocker lock(&socketOperationMutex);
emit callForDisconnect();
socketThread->quit();
}
QAbstractSocket::SocketError BlockingSocket::getErrorCode()
{
QMutexLocker lock(&socketOperationMutex);
return socket->getErrorCode();
}
QString BlockingSocket::getErrorText()
{
QMutexLocker lock(&socketOperationMutex);
return socket->getErrorText();
}
bool BlockingSocket::connectToHost(const QString& host, int port)
{
QMutexLocker lock(&socketOperationMutex);
bool res = false;
emit callForConnect(host, port, res);
return res;
}
void BlockingSocket::disconnectFromHost()
{
QMutexLocker lock(&socketOperationMutex);
emit callForDisconnect();
}
bool BlockingSocket::isConnected()
{
QMutexLocker lock(&socketOperationMutex);
bool res = false;
emit callForIsConnected(res);
return res;
}
bool BlockingSocket::send(const QByteArray& bytes)
{
QMutexLocker lock(&socketOperationMutex);
bool res = false;
emit callForSend(bytes, res);
return res;
}
QByteArray BlockingSocket::read(qint64 count, int timeout, bool* ok)
{
QMutexLocker lock(&socketOperationMutex);
bool res = false;
QByteArray bytes;
emit callForRead(count, timeout, bytes, res);
if (ok)
*ok = res;
return bytes;
}
void BlockingSocket::quit()
{
QMutexLocker lock(&socketOperationMutex);
socketThread->quit();
}
void BlockingSocket::exit()
{
QMutexLocker lock(&socketOperationMutex);
socketThread->quit();
}
|