QObject :: connect在QRunnable中 - 控制台

时间:2013-11-18 11:47:17

标签: qt connect qtcpsocket disconnected

我创建简单的多线程服务器:

  • 创建服务器
  • 如果新连接创建新的QThreadpool - QRunnable
  • 在runnable发送消息给客户端并等待请求
  • 如果客户端已断开连接,则运行写入qDebug并运行runnable quit。

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);

!!!怎么做??? ??? QObgect :: connect(newSocketCon,SIGNAL(disconnected()),this,SLOTS(disconnectCln()));

newSocketCon->write(mes.toUtf8().data());
newSocketCon->flush();
newSocketCon->waitForBytesWritten();
}

void Runnable::disconnectCln()
{
qDebug() << "Client was disconnect";
}

1 个答案:

答案 0 :(得分:11)

你似乎忽略了实际问一个问题,但这是我用你的代码发现的直接问题:你的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宏。