-
Notifications
You must be signed in to change notification settings - Fork 11
/
tcpserver.cpp
74 lines (67 loc) · 2.03 KB
/
tcpserver.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include "tcpserver.h"
#include "subreactor.h"
#include "thread.h"
class TcpServerPrivate
{
public:
explicit TcpServerPrivate(QObject *parent)
: owner(parent)
{}
QObject *owner;
QVector<Thread *> threads;
SubReactor *subReactor = nullptr;
int index = 0;
};
TcpServer::TcpServer(int num, QObject *parent)
: QTcpServer(parent)
, d(new TcpServerPrivate(this))
{
qRegisterMetaType<qintptr>("qintptr");
qRegisterMetaType<QAtomicInt>("QAtomicInt");
for (int i = 0; i < num; i++) { // one Loop Thread
Thread *thread = new Thread(this);
connect(thread, &Thread::message, this, &TcpServer::message);
connect(thread, &Thread::maxCount, this, &TcpServer::maxCount);
connect(thread, &Thread::clientCount, this, &TcpServer::clientCount);
d->threads.append(thread);
thread->start();
}
if (num <= 0) { // one Thread in Accepter
d->subReactor = new SubReactor(this);
connect(d->subReactor, &SubReactor::message, this, &TcpServer::message);
connect(d->subReactor, &SubReactor::maxCount, this, &TcpServer::maxCount);
connect(d->subReactor, &SubReactor::clientCount, this, &TcpServer::clientCount);
}
}
TcpServer::~TcpServer()
{
if (!d->threads.isEmpty()) {
qDeleteAll(d->threads);
d->threads.clear();
}
close();
qDebug() << "~TcpServer";
}
//-------------------------------------------------
// Accepter
//-------------------------------------------------
void TcpServer::incomingConnection(qintptr handle)
{
auto thread = getNextThread();
if (thread != nullptr) {
emit thread->newConnectHandle(handle);
} else if (d->subReactor != nullptr) {
d->subReactor->onNewConnect(handle);
}
}
auto TcpServer::getNextThread() -> Thread *
{
if (d->threads.isEmpty()) {
return nullptr;
}
if (d->index < 0 || d->index >= d->threads.size())
d->index = 0;
Thread *thread = d->threads.at(d->index);
d->index++;
return thread;
}