-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcpsocketconnection.cpp
70 lines (60 loc) · 1.63 KB
/
tcpsocketconnection.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
#include "tcpsocketconnection.h"
TcpSocketConnection::TcpSocketConnection(int ID, QObject *parent, QString fileSize) :
QThread(parent)
{
this->fileSize = fileSize.toInt();
this->socketDescriptor = ID;
}
TcpSocketConnection::~TcpSocketConnection()
{
socket->close();
socket->deleteLater();
}
void TcpSocketConnection::run()
{
qDebug() << "Starting Thread";
socket = new QTcpSocket();
if(!socket->setSocketDescriptor(this->socketDescriptor))
{
emit error(socket->error());
return;
}
connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()), Qt::DirectConnection);
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()), Qt::DirectConnection);
qDebug() << "Client Connected" << socketDescriptor;
exec();
}
void TcpSocketConnection::readyRead()
{
QByteArray data = socket->readAll();
dataHandler(data);
}
void TcpSocketConnection::disconnected()
{
qDebug() << socketDescriptor << " disconnected!";
socket->deleteLater();
exit(0);
}
void TcpSocketConnection::dataHandler(QByteArray data)
{
QFile file(fileName);
if(!file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
{
qDebug() << "Failed to open file.";
return;
}
if (file.size() >= fileSize)
{
file.close();
fileName.append(QString::number(i++));
file.setFileName(fileName);
if(!file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
{
qDebug() << "Failed to open file.";
return;
}
}
QTextStream ts(&file);
ts << data;
file.close();
}