-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclientside.cpp
More file actions
123 lines (80 loc) · 2.21 KB
/
clientside.cpp
File metadata and controls
123 lines (80 loc) · 2.21 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
#include "clientside.h"
ClientSide::ClientSide(const QString hostAddress, int portNumber, QObject *parent) : QObject(parent), m_nNextBlockSize(0)
{
status = false;
host = hostAddress;
port = portNumber;
tcpSocket = new QTcpSocket(this);
connect(tcpSocket, &QTcpSocket::disconnected, this, &ClientSide::closeConnection);
timeoutTimer = new QTimer();
timeoutTimer->setSingleShot(true);
connect(timeoutTimer, &QTimer::timeout, this, &ClientSide::connectionTimeout);
}
void ClientSide::connect2host()
{
timeoutTimer->start(3000);
tcpSocket->connectToHost(host, port);
connect(tcpSocket, &QTcpSocket::connected, this, &ClientSide::connected);
connect(tcpSocket, &QTcpSocket::readyRead, this, &ClientSide::readyRead);
}
void ClientSide::connectionTimeout()
{
if(tcpSocket->state() == QAbstractSocket::ConnectingState)
{
tcpSocket->abort();
emit tcpSocket->error(QAbstractSocket::SocketTimeoutError);
}
}
void ClientSide::connected()
{
status = true;
emit statusChanged(status);
}
bool ClientSide::getStatus() {return status;}
void ClientSide::readyRead()
{
QDataStream in (tcpSocket);
for(;;)
{
if(!m_nNextBlockSize)
{
if(tcpSocket->bytesAvailable() < sizeof(quint16)) {break;}
in >> m_nNextBlockSize;
}
if(tcpSocket->bytesAvailable() < m_nNextBlockSize) {break;}
QString str;
in >> str;
if(str == "0")
{
str = "Connection closed";
closeConnection();
}
emit hasReadSome(str);
m_nNextBlockSize = 0;
}
}
void ClientSide::closeConnection()
{
timeoutTimer->stop();
disconnect(tcpSocket, &QTcpSocket::connected, 0,0);
disconnect(tcpSocket, &QTcpSocket::readyRead, 0, 0);
bool shouldEmit = false;
switch (tcpSocket->state())
{
case 0:
tcpSocket->disconnectFromHost();
shouldEmit = true;
break;
case 2:
tcpSocket->abort();
shouldEmit = true;
break;
default:
tcpSocket->abort();
}
if(shouldEmit)
{
status = false;
emit statusChanged(status);
}
}