/
icserver.cpp
190 lines (153 loc) · 6.51 KB
/
icserver.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
#include "icserver.h"
#include <QTimer>
#include <QThreadPool>
#include "icmessagehandler.h"
#include "icmessage.h"
#include "icquestion.h"
#include "icsystemstore.h"
#include "icconfig.h"
#include "icmessageprocessor.h"
ICServer::ICServer(QObject *parent) :
QObject(parent), settings(new QSettings(CONFIG_FILE, QSettings::IniFormat, this))
{
isRunning = false;
}
void ICServer::setUp(QString identifier, QHostAddress address)
{
sid = identifier;
ipAddress = address;
}
QString ICServer::getIdentifier() const { return sid; }
bool ICServer::startSidTest(int duration)
{
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(stopSidTest()));
timer->setInterval(duration);
timer->setSingleShot(true);
testUdpSocket = new QUdpSocket(this);
bool success = testUdpSocket->bind(ipAddress, CLIENT_PORT);
// if bind failed
if (!success) return false;
connect(testUdpSocket, SIGNAL(readyRead()), this, SLOT(processPendingDatagrams()));
ICMessage question = ICMessage::initWithCommonProperties();
question.setProperty(settings->value(SID_CONFIG_TAG,DEFAULT_SID_TAG).toString(),sid);
question.setProperty(settings->value(COMMAND_CONFIG_TAG,DEFAULT_CMD_TAG).toString(), QString::number(SERVER_DISCOVERY));
// broadcast for three times
for (int i = 0; i < 3; i++)
testUdpSocket->writeDatagram(question.saveAsJson(), QHostAddress::Broadcast, SERVER_PORT);
timer->start();
return true;
}
void ICServer::stopSidTest()
{
if (testUdpSocket != 0) {
testUdpSocket->close();
}
}
// not in use
void ICServer::socketClosed(QAbstractSocket::SocketError)
{
emit connectionClosed();
}
// listen on port 8027, broadcast question to 8026
bool ICServer::listen()
{
udpSocket = new QUdpSocket(this);
if (udpSocket->bind(ipAddress, SERVER_PORT)) {
connect(udpSocket, SIGNAL(readyRead()), this, SLOT(processPendingDatagrams()));
//connect(udpSocket,SIGNAL(error(QAbstractSocket::SocketError)),this, SLOT(socketClosed(QAbstractSocket::SocketError)));
isRunning = true;
return true;
} else return false;
}
// stop the server
void ICServer::stop()
{
if (udpSocket != 0) {
udpSocket->close();
isRunning = false;
}
}
void ICServer::processPendingDatagrams()
{
QByteArray datagram;
QUdpSocket *socket = isRunning ? udpSocket : testUdpSocket;
do {
QHostAddress *address = new QHostAddress;
datagram.resize(socket->pendingDatagramSize());
socket->readDatagram(datagram.data(), datagram.size(), address);
ICMessageHandler *messageHandler = new ICMessageHandler(this);
connect(messageHandler, SIGNAL(connectionOffer(QString)), this, SLOT(processSidCollision(QString)));
connect(messageHandler, SIGNAL(serverDiscovery(QHostAddress,QString)), this, SLOT(processDiscovery(QHostAddress,QString)));
connect(messageHandler, SIGNAL(questionRequest(QHostAddress)), this, SLOT(processRequest(QHostAddress)));
connect(messageHandler, SIGNAL(answerReady(ICAnswer,QString)), this, SLOT(processAnswer(ICAnswer,QString)));
ICMessageProcessor *processor = new ICMessageProcessor(messageHandler, *address, datagram);
QThreadPool::globalInstance()->start(processor);
qDebug()<< "[1] Received from " << *address << datagram;
delete address;
} while (socket->hasPendingDatagrams());
}
void ICServer::broadcastQuestion()
{
ICQuestion currentQuestion = ICSystemStore::getInstance()->getCurrentQuestion();
if (!currentQuestion.isNull()) {
ICMessage question = ICMessage::initWithCommonProperties();
question.setProperty(settings->value(SID_CONFIG_TAG,DEFAULT_SID_TAG).toString(),sid);
question.setProperty(settings->value(COMMAND_CONFIG_TAG,DEFAULT_CMD_TAG).toString(), QString::number(QUESTION_DELIVER));
QList<ICQuestion> questions;
questions.append(currentQuestion);
question.setQuestions(questions);
udpSocket->writeDatagram(question.saveAsJson(), QHostAddress::Broadcast, CLIENT_PORT);
}
}
// clientAddress requests a question
// make sure they run in sender's thread
void ICServer::processRequest(QHostAddress clientAddress)
{
ICQuestion currentQuestion = ICSystemStore::getInstance()->getCurrentQuestion();
ICMessage reply = ICMessage::initWithCommonProperties();
if (currentQuestion.isNull()) {
reply.setProperty(settings->value(SID_CONFIG_TAG,DEFAULT_SID_TAG).toString(),sid);
reply.setProperty(settings->value(COMMAND_CONFIG_TAG,DEFAULT_CMD_TAG).toString(), QString::number(NOT_QUESTIONING));
}
else {
reply.setProperty(settings->value(SID_CONFIG_TAG,DEFAULT_SID_TAG).toString(),sid);
reply.setProperty(settings->value(COMMAND_CONFIG_TAG,DEFAULT_CMD_TAG).toString(), QString::number(QUESTION_DELIVER));
QList<ICQuestion> questions;
questions.append(currentQuestion);
reply.setQuestions(questions);
}
udpSocket->writeDatagram(reply.saveAsJson(), clientAddress, CLIENT_PORT);
qDebug() << "[2] Send to " << clientAddress << reply.saveAsJson() << " in thread " << QThread::currentThread();
}
// a connection offer with identifier comes
void ICServer::processSidCollision(QString identifier)
{
if (sid.compare(identifier) == 0)
{
emit identifierCollision(sid);
}
}
// a server discovery with specified identifier comes
void ICServer::processDiscovery(QHostAddress clientAddress, QString identifier)
{
if (sid.compare(identifier) == 0) {
ICMessage connectionOffer = ICMessage::initWithCommonProperties();
connectionOffer.setProperty(settings->value(SID_CONFIG_TAG,DEFAULT_SID_TAG).toString(),sid);
connectionOffer.setProperty(settings->value(COMMAND_CONFIG_TAG,DEFAULT_CMD_TAG).toString(), QString::number(CONNECTION_OFFER));
udpSocket->writeDatagram(connectionOffer.saveAsJson(), clientAddress, CLIENT_PORT);
qDebug() << "[3] Send to " << clientAddress << connectionOffer.saveAsJson() << " in thread " << QThread::currentThread();
}
}
// an answer come with sender's uid
void ICServer::processAnswer(ICAnswer answer, QString uid)
{
ICSystemStore *store = ICSystemStore::getInstance();
ICQuestion currentQuestion = store->getCurrentQuestion();
if (!currentQuestion.isNull() && currentQuestion.getId().compare(answer.getId()) == 0) {
answer.setUid(uid);
store->addAnswer(answer);
emit newAnswerArrived(uid);
qDebug() << "[4] Answer from " << uid << "processed" << " in thread " << QThread::currentThread();
}
}