QObject :: connect在QRunnable中 - 控制台

3 qt connect disconnected qtcpsocket

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

  • 创建服务器
  • 如果新连接创建新的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;
};
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

runnable.h

class Runnable : public QRunnable
{
public:
Runnable();
int SocketDescriptor;

protected:
void run();

public slots:
void disconnectCln();
};
Run Code Online (Sandbox Code Playgroud)

runnable.cpp

#include "runnable.h"

Runnable::Runnable()
{

}

void Runnable::run()
{
if(!SocketDescriptor) return;

QTcpSocket *newSocketCon = new QTcpSocket();
newSocketCon->setSocketDescriptor(SocketDescriptor);
Run Code Online (Sandbox Code Playgroud)

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

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

void Runnable::disconnectCln()
{
qDebug() << "Client was disconnect";
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*urn 12

你似乎忽略了实际问一个问题,但这是我用你的代码发现的直接问题:你的Runnable类没有从QObject继承,因此不能有信号和插槽.你需要这样做才能让它成功.

class Runnable : public QObject, public QRunnable
{
  Q_OBJECT
public:
  Runnable();
  int SocketDescriptor;

protected:
  void run();

public slots:
  void disconnectCln();
};
Run Code Online (Sandbox Code Playgroud)

这里有两件重要的事情需要注意.1)如果你使用多重继承,QObject必须先在列表中.2)要使用信号和插槽,必须Q_OBJECT在类定义中包含宏.