-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtcpclinet.cpp
121 lines (99 loc) · 2.73 KB
/
tcpclinet.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
#include "tcpclinet.h"
TcpClient::TcpClient()
{
hostip = new QHostAddress();
clientsocket = new QTcpSocket();
isConnected = false;
}
TcpClient::~TcpClient()
{
close();
delete[] hostip;
delete[] clientsocket;
}
int TcpClient::run(QString ipserver, quint16 port)
{
//close();
if(!hostip->setAddress(ipserver))
return -1;
_port = port;
clientsocket->connectToHost(*hostip, port);
connect(clientsocket, SIGNAL(connected()), this, SLOT(slotconnectedsuccess()));
int loop = 0;
while(!clientsocket->waitForConnected(5000))
{
loop++;
QMutex mutex;
QWaitCondition sleep;
mutex.lock();
sleep.wait(&mutex, 1000);
mutex.unlock();
qDebug() << loop << "th reconnect to the server";
clientsocket->connectToHost(*hostip, port);
}
if(!clientsocket->waitForConnected(5000))
return -2;
//接收到服务器的信息就会触发readyRead信号
connect(clientsocket, SIGNAL(readyRead()), this, SLOT(receivedata()));
// 断开服务器信号
connect(clientsocket, SIGNAL(disconnected()), this, SLOT(slotdisconnected()));
return 1;
}
int TcpClient::reconnect()
{
clientsocket->disconnectFromHost();
clientsocket->connectToHost(*hostip, _port);
QDateTime time1 = QDateTime::currentDateTime(), time2;
if(!clientsocket->waitForConnected(5000))
{
QMutex mutex;
QWaitCondition sleep;
time2 = QDateTime::currentDateTime();
int dis = time1.msecsTo(QDateTime::currentDateTime());
mutex.lock();
sleep.wait(&mutex, dis + 1);
mutex.unlock();
return -2;
}
return 1;
}
void TcpClient::slotconnectedsuccess()
{
isConnected = 1;
QString str = "Client: " +
clientsocket->localAddress().toString() +
"." + QString::number(clientsocket->localPort()) +
" connects to server ^_^.\n";
clientsocket->write(str.toUtf8());
}
void TcpClient::slotdisconnected()
{
isConnected = 0;
}
void TcpClient::receivedata()
{
QByteArray array = clientsocket->readAll();
emit signals_socket_receive(array);
#ifdef DEBUG_TCP_CLIENT_RECEIVE
QString hexstr = ByteArrayToHexString(array);
printf("Client receive: %s\n", hexstr.toStdString().c_str());
#endif
}
void TcpClient::close()
{
if(hostip != nullptr)
{
hostip->clear();
}
if(clientsocket != nullptr)
{
clientsocket->disconnectFromHost();
clientsocket->waitForDisconnected();
clientsocket->close();
}
isConnected = false;
}
void TcpClient::send(QByteArray tcpdata)
{
clientsocket->write(tcpdata);
}