4

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

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

服务器.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);
}

可运行的.h

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

protected:
void run();

public slots:
void disconnectCln();
};

可运行的.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";
}
4

1 回答 1

16

您似乎忽略了实际提出问题,但这是我在您的代码中发现的直接问题:您的 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在类定义中包含宏。

于 2013-11-18T13:59:30.820 回答