-
Notifications
You must be signed in to change notification settings - Fork 12
/
tcpclientthread.cpp
60 lines (55 loc) · 1.71 KB
/
tcpclientthread.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
#include "tcpclientthread.h"
#include "tcpclient.h"
class TcpClientThreadPrivate{
public:
explicit TcpClientThreadPrivate(QThread *parent = nullptr)
: owner(parent){}
QThread *owner;
QString ip = "127.0.0.1";
quint16 port = 65533;
int index = 0;
};
TcpClientThread::TcpClientThread(const QString &ip,
const quint16 port,
const int index,
QObject *parent)
: QThread(parent)
, d(new TcpClientThreadPrivate)
{
d->ip = ip;
d->port = port;
d->index = index;
}
TcpClientThread::~TcpClientThread(){
if(isRunning()){
quit();
wait();
}
qDebug() << "~Thread" << d->index;
}
void TcpClientThread::removeMyself()
{
emit quitThread(d->index);
}
void TcpClientThread::run()
{
QScopedPointer<TcpClient> client(new TcpClient);
client->connectToHost(d->ip, d->port);
if(!client->waitForConnected(1000)){
qWarning() << tr("connection failed fd: ")
<< client->errorString();
emit quitThread(d->index);
return;
}
// while(!client->waitForConnected(3000)){
// client->connectToHost(ip, quint16(port));
// qWarning() << tr("connection failed fd: ")
// << client->errorString();
// }
qDebug() << "New Client: " << d->index << QThread::currentThreadId();
connect(this, &TcpClientThread::writeToServer, client.data(), &TcpClient::onWrite);
connect(client.data(), &TcpClient::readyRead,
client.data(), &TcpClient::onReadyRead, Qt::DirectConnection);
connect(client.data(), &TcpClient::disconnected, this, &TcpClientThread::removeMyself);
exec();
}