-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcp_server.cpp
353 lines (301 loc) · 8.62 KB
/
tcp_server.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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/*
qCommTest - Serial Communication Test Tool
Version : 1.0
Date : 20.11.2017
Author : Eray Ozturk | github.com/diffstorm
*/
#include "tcp_server.h"
// TODO : Adaptive timeout determined by network latency measurement
#define TCP_TIMEOUT(x) (5 + x/500) // [ms]
TcpServer::TcpServer()
{
m_socket = nullptr;
m_tcpServer = new QTcpServer(this);
m_tcpServer->setMaxPendingConnections(1);
m_clientIp = "";
m_clientConnected = false;
connect(m_tcpServer, &QTcpServer::newConnection, this, &TcpServer::onNewClientConnection);
connect(&m_timer_rx, &QTimer::timeout, this, &TcpServer::onTimeoutRX);
connect(&m_timer_tx, &QTimer::timeout, this, &TcpServer::onTimeoutTX);
m_timer_tx.setSingleShot(true);
m_timer_tx.stop();
m_timer_rx.setSingleShot(true);
m_timer_rx.stop();
m_dataReceivedAt = 0;
m_dataSentAt = 0;
}
TcpServer::~TcpServer()
{
stopServer();
delete m_socket;
delete m_tcpServer;
}
void TcpServer::Log(const QString &log)
{
emit logMessage("TCP Server : " + log);
}
qint64 TcpServer::getReceivedTime()
{
return m_dataReceivedAt;
}
qint64 TcpServer::getSentTime()
{
return m_dataSentAt;
}
qint64 TcpServer::getTimeout(qint64 data_size)
{
return TCP_TIMEOUT(data_size);
}
QString TcpServer::getClientIp() const
{
return m_clientIp;
}
void TcpServer::setClientIp(const QString &value)
{
m_clientIp = value;
}
int TcpServer::getServerPort() const
{
return m_serverPort;
}
bool TcpServer::startServer(const int &value)
{
bool ret;
m_serverPort = value;
if(m_tcpServer->isListening())
{
stopServer();
}
ret = m_tcpServer->listen(QHostAddress::Any, m_serverPort);
if(false != ret)
{
Log(QString("Started listening on port %1").arg(m_serverPort));
}
else
{
Log("Start failed, error:" + m_tcpServer->errorString());
}
return ret;
}
void TcpServer::stopServer()
{
if(m_tcpServer->isListening() && nullptr != m_socket)
{
waitForBytesWritten();
}
m_tcpServer->close();
if(m_socket != nullptr)
{
m_socket->close();
}
m_timer_rx.stop();
m_timer_tx.stop();
Log("Stopped");
}
void TcpServer::waitForBytesWritten()
{
qint64 bytesToWrite = m_socket->bytesToWrite();
if(bytesToWrite)
{
qDebug() << "Busy! Waiting" << TCP_TIMEOUT(bytesToWrite) << "ms to write" << bytesToWrite << "bytes";
m_socket->waitForBytesWritten(TCP_TIMEOUT(bytesToWrite));
}
}
bool TcpServer::isListenning()
{
return m_tcpServer->isListening();
}
bool TcpServer::isClientConnected() const
{
return m_clientConnected;
}
void TcpServer::onNewClientConnection()
{
if(nullptr != m_socket)
{
m_socket->close();
delete m_socket;
}
m_socket = m_tcpServer->nextPendingConnection();
//m_socket->setSocketOption(QAbstractSocket::KeepAliveOption, 1);
m_socket->flush();
m_socket->setReadBufferSize(4096);
if(m_socket->isValid())
{
onClientConnectedSlot();
}
connect(m_socket, &QTcpSocket::connected, this, &TcpServer::onClientConnectedSlot);
connect(m_socket, &QTcpSocket::disconnected, this, &TcpServer::onClientDisconnectedSlot);
connect(m_socket, &QTcpSocket::errorOccurred, this, &TcpServer::onSocketErrorOccured);
connect(m_socket, &QTcpSocket::readyRead, this, &TcpServer::dataReceivedSlot);
connect(m_socket, &QTcpSocket::bytesWritten, this, &TcpServer::onBytesWritten);
setClientIp(m_socket->localAddress().toString());
}
void TcpServer::onClientConnectedSlot()
{
Log("Client connected");
m_clientConnected = true;
emit clientConnected();
}
void TcpServer::onClientDisconnectedSlot()
{
Log("Client disconnected");
m_clientConnected = false;
emit clientDisconnected();
}
bool TcpServer::Write(const QByteArray &writeData)
{
bool ret = false;
if(!m_socket->isValid())
{
qDebug() << "Invalid socket to send";
}
else
{
waitForBytesWritten();
if(m_socket->state() == QTcpSocket::ConnectedState &&
m_socket->isWritable())
{
m_writeData.clear();
m_writeData = writeData;
m_dataSentAt = QDateTime::currentMSecsSinceEpoch();
qDebug() << "Bytes to write :" << writeData.size();
qint64 bytesWritten = m_socket->write(writeData);
if(bytesWritten == -1)
{
qDebug() << "Failed to write the data -" << "error:" << m_socket->errorString();
}
else if(bytesWritten != m_writeData.size())
{
qDebug() << "Failed to write all the data -" << "error:" << m_socket->errorString();
}
else if(bytesWritten == m_writeData.size())
{
ret = true;
qDebug() << "Buffer write successful";
}
qDebug() << "Remaining bytes to write :" << m_socket->bytesToWrite();
qDebug() << "Write timeout is set to" << TCP_TIMEOUT(m_writeData.size()) << "ms to write" << m_writeData.size() << "bytes";
m_timer_tx.start(TCP_TIMEOUT(m_writeData.size()));
}
else
{
qDebug() << "Tcp connection is not active";
}
}
return ret;
}
QByteArray TcpServer::Read()
{
QByteArray readData;
if(m_socket->isReadable())
{
qint64 bytesAvailable = m_socket->bytesAvailable();
if(bytesAvailable > 0)
{
qDebug() << "Busy! Waiting" << TCP_TIMEOUT(bytesAvailable) << "ms to read" << bytesAvailable << "bytes";
m_socket->waitForReadyRead(TCP_TIMEOUT(bytesAvailable));
}
}
else
{
qDebug() << "Socket is not readable";
}
readData = m_readData;
m_readData.clear();
Log(QString("Read %1 bytes").arg(readData.size()));
return readData;
}
void TcpServer::dataReceivedSlot()
{
qDebug() << "Data received.";
if(!m_socket->isValid())
{
qDebug() << "Invalid socket to read";
return;
}
if(m_socket->bytesAvailable() > 0 &&
m_socket->isReadable())
{
qint64 bytesAvailable = m_socket->bytesAvailable();
qDebug() << bytesAvailable << "bytes are available to read";
if(bytesAvailable > 0)
{
m_readData.append(m_socket->readAll());
m_dataReceivedAt = QDateTime::currentMSecsSinceEpoch();
}
qDebug() << "Read timeout is set to" << TCP_TIMEOUT(bytesAvailable) << "ms to read" << bytesAvailable << "bytes";
m_timer_rx.start(TCP_TIMEOUT(bytesAvailable));
}
else
{
qDebug() << "Tcp connection is not active";
}
}
void TcpServer::onBytesWritten(qint64 bytes)
{
m_bytesWritten += bytes;
if(m_bytesWritten == m_writeData.size())
{
m_timer_tx.stop();
m_bytesWritten = 0;
qDebug() << "Data successfully sent";
Log(QString("Written %1 bytes").arg(m_writeData.size()));
//qDebug() << QString("TX:" + m_writeData.toHex());
}
else
{
qint64 bytesToWrite = m_writeData.size() - m_bytesWritten;
qDebug() << "Written" << m_bytesWritten << "/" << m_writeData.size();
qDebug() << "Write timeout is set to" << TCP_TIMEOUT(bytesToWrite) << "ms to write" << bytesToWrite << "bytes";
m_timer_tx.start(TCP_TIMEOUT(bytesToWrite));
}
}
void TcpServer::onTimeoutTX()
{
if(m_bytesWritten != m_writeData.size())
{
Log("Write operation timed out");
qDebug() << "Write operation timed out";
qDebug() << "error:" << m_socket->errorString();
}
else
{
qDebug() << "Data sent succeeded but timeout occurred";
}
}
void TcpServer::onTimeoutRX()
{
if(m_readData.isEmpty())
{
qDebug() << "No data was currently available for reading";
}
else
{
qDebug() << "Data successfully received";
qDebug() << m_readData.length() << "bytes received.";
//qDebug() << QString("RX:" + m_readData.toHex());
emit dataReceived();
}
}
void TcpServer::onSocketErrorOccured(QAbstractSocket::SocketError err)
{
switch(err)
{
case QTcpSocket::RemoteHostClosedError:
{
qint64 diff = QDateTime::currentMSecsSinceEpoch() - m_dataSentAt;
if(200 < diff) // 100 ms is signal time
{
qDebug() << "The remote host closed the connection";
}
}
break;
case QTcpSocket::ConnectionRefusedError:
qDebug() << "TCP Connection refused";
break;
default:
qCritical() << "TCP socket error:" << err << "-" << m_socket->errorString();
break;
}
}