-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtcpclient.cpp
More file actions
126 lines (111 loc) · 2.67 KB
/
Copy pathtcpclient.cpp
File metadata and controls
126 lines (111 loc) · 2.67 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
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
#include "tcpclient.h"
#include <QDataStream>
#include <QDateTime>
#include <QDebug>
/**
* @brief Class constructor
* @param parent
*/
TcpClient::TcpClient(QObject *parent) : QObject(parent)
{
tcpSocket = new QTcpSocket(this);
tcpSocket->setSocketOption(QAbstractSocket::LowDelayOption,
QVariant::fromValue(1));
connect(tcpSocket, SIGNAL(connected()), SLOT(slotConnected()));
connect(tcpSocket, SIGNAL(disconnected()), SLOT(slotDisconnected()));
connect(tcpSocket, SIGNAL(readyRead()), SLOT(slotReadyRead()));
connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(slotError(QAbstractSocket::SocketError)));
}
/**
* @brief Class dectructor
*/
TcpClient::~TcpClient()
{
qDebug() <<"By-by from" <<this;
if (tcpSocket->isOpen()) {
tcpSocket->close();
}
emit quitTcpClient();
}
/**
* @brief MyTcpClient::onClientStart
*/
void TcpClient::onClientStart()
{
}
/**
* @brief MyTcpClient::slotReadyRead
*/
void TcpClient::slotReadyRead()
{
QByteArray data;
for (;;) {
data += tcpSocket->readAll();
if (tcpSocket->bytesAvailable() < 1) {
break;
}
}
if (!data.isEmpty()) {
emit showResponse((QByteArray&)data);
}
}
/**
* @brief MyTcpClient::slotError
* @param err
*/
void TcpClient::slotError(QAbstractSocket::SocketError err)
{
QString strError =
"Error: " + (err == QAbstractSocket::HostNotFoundError ?
"The host was not found." :
err == QAbstractSocket::RemoteHostClosedError ?
"The remote host is closed." :
err == QAbstractSocket::ConnectionRefusedError ?
"The connection was refused." :
QString(tcpSocket->errorString())
);
QByteArray errMsg;
errMsg.append(strError.toUtf8());
emit showResponse(errMsg);
qDebug() << strError;
}
/**
* @brief MyTcpClient::slotConnected
*/
void TcpClient::slotConnected()
{
emit confirmTcpConnection(true);
}
/**
* @brief MyTcpClient::slotDisconnected
*/
void TcpClient::slotDisconnected()
{
emit confirmTcpConnection(false);
}
/**
* @brief MyTcpClient::onSetTcpConnection
* @param hostName
* @param port
*/
void TcpClient::onSetTcpConnection(const QString &hostName, quint16 port)
{
tcpSocket->connectToHost(hostName, port);
}
/**
* @brief MyTcpClient::onSetTcpDisconnection
*/
void TcpClient::onSetTcpDisconnection()
{
tcpSocket->close();
}
/**
* @brief MyTcpClient::onSendToServer
* @param msg
*/
void TcpClient::onSendToServer(const QByteArray &msg)
{
tcpSocket->write(msg);
tcpSocket->flush();
}