#pragma once
#include "LkTcpSocket.h"
#include <QThread>
class LkTcpThread : public QThread
{
Q_OBJECT
public:
LkTcpThread(int socketDescriptor, QObject *parent = 0);
~LkTcpThread();
void init(int socketDescriptor);
void run();
void write(QByteArray ba);
public slots:
void readDatagrams();
void deleteSocket();
signals:
void deleteSocketSignal(int );
public:
int mSocketDescriptor;
private:
LkTcpSocket *mTcpSocket;
};
#include "LkTcpThread.h"
#include <QDataStream>
#include <QCoreApplication>
#include "Listener/LkListener.h"
LkTcpThread::LkTcpThread(int socketDescriptor, QObject *parent)
: QThread(parent)
{
init(socketDescriptor);
}
LkTcpThread::~LkTcpThread()
{
}
void LkTcpThread::init(int socketDescriptor)
{
mSocketDescriptor = socketDescriptor;
}
void LkTcpThread::run()
{
mTcpSocket = new LkTcpSocket();
mTcpSocket->setSocketDescriptor(mSocketDescriptor);
connect(mTcpSocket, SIGNAL(readyRead()), mTcpSocket, SLOT(readDatagrams()));
connect(mTcpSocket, &QTcpSocket::disconnected, this, &LkTcpThread::deleteSocket);
while (mTcpSocket->isOpen())
{
msleep(1);
QCoreApplication::processEvents();
}
mTcpSocket->disconnectFromHost();
mTcpSocket->waitForDisconnected();
mTcpSocket->close();
}
void LkTcpThread::write(QByteArray ba)
{
mTcpSocket->sendMessage(ba);
}
void LkTcpThread::readDatagrams()
{
QDataStream in(mTcpSocket);
in.setVersion(QDataStream::Qt_5_12);
if (mTcpSocket->bytesAvailable() < sizeof(quint32))
return;
int size = mTcpSocket->bytesAvailable();
QByteArray currentData(size, 0);
in.readRawData(currentData.data(), size);
QDataStream out(currentData);
int type = 0;
out.readRawData((char*)&type, 4);
LkMessageEvent me(QString::number(type));
int dd = currentData.length() - sizeof(int);
me.setData(currentData.length() - sizeof(int), currentData.data() + sizeof(int));
gNetListener->dispatch(me);
}
void LkTcpThread::deleteSocket()
{
mTcpSocket->close();
emit deleteSocketSignal(mSocketDescriptor);
}