I create simple multi threading server:
server.h
class Server : public QTcpServer
{
Q_OBJECT
public:
explicit Server(QObject *parent = 0);
void StartServer();
protected:
void incomingConnection(int handle);
private:
QThreadPool *pool;
};
server.cpp:
#include "server.h"
Server::Server(QObject *parent) :
QTcpServer(parent)
{
pool = new QThreadPool(this);
pool->setMaxThreadCount(10);
}
void Server::StartServer()
{
this->listen(QHostAddress(dts.ipAddress),80));
}
void Server::incomingConnection(int handle)
{
Runnable *task = new Runnable();
task->setAutoDelete(true);
task->SocketDescriptor = handle;
pool->start(task);
}
runnable.h
class Runnable : public QRunnable
{
public:
Runnable();
int SocketDescriptor;
protected:
void run();
public slots:
void disconnectCln();
};
runnable.cpp
#include "runnable.h"
Runnable::Runnable()
{
}
void Runnable::run()
{
if(!SocketDescriptor) return;
QTcpSocket *newSocketCon = new QTcpSocket();
newSocketCon->setSocketDescriptor(SocketDescriptor);
!!! How make it???!!! QObgect::connect(newSocketCon, SIGNAL(disconnected()), this, SLOTS(disconnectCln()));
newSocketCon->write(mes.toUtf8().data());
newSocketCon->flush();
newSocketCon->waitForBytesWritten();
}
void Runnable::disconnectCln()
{
qDebug() << "Client was disconnect";
}
You seem to have neglected to actually ask a question, but here's the immediate problem I spot with your code: Your Runnable class does not inherit from QObject, and thus cannot have signals and slots. You will need to do that to have any hope of making it work.
class Runnable : public QObject, public QRunnable
{
Q_OBJECT
public:
Runnable();
int SocketDescriptor;
protected:
void run();
public slots:
void disconnectCln();
};
There are two important things to note here. 1) if you use multiple inheritance, QObject
must come first in the list. 2) To use signals and slots you must include the Q_OBJECT
macro in your class definition.