我创建了简单的多线程服务器:
服务器.h
class Server : public QTcpServer
{
Q_OBJECT
public:
explicit Server(QObject *parent = 0);
void StartServer();
protected:
void incomingConnection(int handle);
private:
QThreadPool *pool;
};
服务器.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);
}
可运行文件
class Runnable : public QRunnable
{
public:
Runnable();
int SocketDescriptor;
protected:
void run();
public slots:
void disconnectCln();
};
可运行文件
#include "runnable.h"
Runnable::Runnable()
{
}
void Runnable::run()
{
if(!SocketDescriptor) return;
QTcpSocket *newSocketCon = new QTcpSocket();
newSocketCon->setSocketDescriptor(SocketDescriptor);
!!!怎么弄的???!!! QObgect::connect(newSocketCon, SIGNAL(disconnected()), this, SLOTS(disconnectCln()));
newSocketCon->write(mes.toUtf8().data());
newSocketCon->flush();
newSocketCon->waitForBytesWritten();
}
void Runnable::disconnectCln()
{
qDebug() << "Client was disconnect";
}
最佳答案
您似乎忽略了实际提出问题,但这是我在您的代码中发现的直接问题:您的 Runnable 类不是从 QObject 继承的,因此不能有信号和插槽。您需要这样做才能有希望让它发挥作用。
class Runnable : public QObject, public QRunnable
{
Q_OBJECT
public:
Runnable();
int SocketDescriptor;
protected:
void run();
public slots:
void disconnectCln();
};
这里有两件重要的事情需要注意。 1) 如果使用多重继承,
QObject
必须排在列表的第一位。 2) 要使用信号和槽,您必须在类定义中包含 Q_OBJECT
宏。关于qt - QObject::connect in QRunnable - 控制台,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20047001/