-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClientThread.cpp
96 lines (68 loc) · 2.1 KB
/
ClientThread.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
#include "ClientThread.h"
#include "ChattingClient.h"
#include "Message.h"
#include <QThread>
#include <QString>
#include <QTcpSocket>
#include <QObject>
#include <QDebug>
ClientThread::ClientThread(QString name, QString ip, QObject* parent) {
this->parent = parent;
this->name = name;
this->ip = ip;
}
void ClientThread::run() {
QByteArray response;
QByteArray name = this->name.toUtf8();
qDebug() << "Starting client thread";
socket = new QTcpSocket(this);
socket->connectToHost(this->ip, 1234);
if (socket->waitForConnected(3000)) {
qDebug() << "Connected";
}
else {
qDebug() << "something went wrong";
exit();
}
this->socketDescriptor = socket->socketDescriptor();
qDebug() << "Waiting for server init";
socket->waitForReadyRead(3000);
qDebug() << "Reading: " << socket->bytesAvailable();
response = socket->readAll();
qDebug() << "Server init response: " << response;
if (response != "200;Server connection establisehd") {
qDebug() << "Something was wrong with the servers response";
}
qDebug() << "Sending name: " << name;
socket->write(name);
response = socket->readAll();
qDebug() << "Thread officially created";
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
connect(socket, SIGNAL(readyRead()), this, SLOT(onNewData()));
exec();
}
void ClientThread::onNewData() {
qDebug() << "Casting client";
ChattingClient* pChatClient = dynamic_cast<ChattingClient*>(parent);
qDebug() << "Recieving server data";
QByteArray data = socket->readAll();
qDebug() << "Server sent" << data;
Message* message = new Message();
qDebug() << "Parsing data";
message->parse(data);
qDebug() << "Adding message";
pChatClient->addMessage(message);
}
void ClientThread::disconnected() {
qDebug() << "Server disconnected";
socket->deleteLater();
exit();
}
void ClientThread::sendMessage(QByteArray content) {
ChattingClient* pChatClient = dynamic_cast<ChattingClient*>(parent);
Message* message = new Message(content, "Me");
qDebug() << "Sending: " << content;
pChatClient->addMessage(message);
this->socket->write(content);
this->socket->waitForBytesWritten();
}