-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclientsocket.cpp
More file actions
94 lines (79 loc) · 2.66 KB
/
clientsocket.cpp
File metadata and controls
94 lines (79 loc) · 2.66 KB
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
#include "clientsocket.h"
ClientSocket::ClientSocket(const qintptr socketId, QObject *parent) :
QObject(parent)
{
// init
serverBuffer = 0;
// create socket
this->tcpSocket = new QTcpSocket(this);
this->socketId = socketId;
// create connections
connect(tcpSocket,SIGNAL(readyRead()),
this, SLOT(receiveData()));
connect(tcpSocket,SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(error(QAbstractSocket::SocketError)));
connect(tcpSocket,SIGNAL(disconnected()),
this, SLOT(finish()));
}
void ClientSocket::start()
{
// disable nagle's algorithm
tcpSocket->setSocketOption(QAbstractSocket::LowDelayOption,1);
// set socket descriptor or close thread if unable to set
if (!tcpSocket->setSocketDescriptor(socketId))
finish();
}
void ClientSocket::close()
{
if (tcpSocket->state() == QTcpSocket::ConnectedState)
tcpSocket->disconnectFromHost();
}
void ClientSocket::error(const QAbstractSocket::SocketError &/*error*/)
{
}
void ClientSocket::finish()
{
// emit done
emit done();
}
void ClientSocket::receiveData()
{
// loop until no data is available
forever
{
if (serverBuffer == nullptr) { // buffer isempty
if (tcpSocket->bytesAvailable() < headerSize())
break;
// read header
QByteArray header = tcpSocket->read(headerSize());
Buffer tmp = {
Invalid,
reinterpret_cast<TPointer*>(header.data()),
headerSize(),
0
};
serverBuffer = createBufferFromHeader(&tmp);
}
// check if all data is received
if (serverBuffer == nullptr || tcpSocket->bytesAvailable() < serverBuffer->size)
break;
// receive data, broadcast and prepare for next data
if (serverBuffer != nullptr) {
// read data
QByteArray data = tcpSocket->read(serverBuffer->size);
memmove(serverBuffer->data, data.data(), serverBuffer->size);
// broadcast
emit dataReceived(serverBuffer, socketId);
// reset buffer -> prepare for next (data deletion is done by the BLoC)
serverBuffer = nullptr;
}
}
}
void ClientSocket::sendData(const QByteArray &data, const qintptr socketId)
{
if (socketId == -1 || socketId == this->socketId) {
if (data.length() > 0) {
tcpSocket->write(data);
}
}
}