-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket.cpp
More file actions
90 lines (73 loc) · 2.26 KB
/
socket.cpp
File metadata and controls
90 lines (73 loc) · 2.26 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
#include "socket.h"
Socket::Socket(QString ip, int port) : networkSession(Q_NULLPTR), _ip(ip), _port(port)
{
}
void Socket::createSocket()
{
tcpSocket = new QTcpSocket();
in.setDevice(tcpSocket);
in.setVersion(QDataStream::Qt_4_0);
connect(tcpSocket, &QIODevice::readyRead, this, &Socket::createSocket);
typedef void (QAbstractSocket::*QAbstractSocketErrorSignal)(QAbstractSocket::SocketError);
connect(tcpSocket, static_cast<QAbstractSocketErrorSignal>(&QAbstractSocket::error), this, &Socket::displayError);
tcpSocket->connectToHost(_ip, _port);
tcpSocket->waitForConnected();
}
void Socket::readFortune()
{
in.startTransaction();
QString nextFortune;
in >> nextFortune;
if (!in.commitTransaction())
return;
if (nextFortune == currentFortune) {
QTimer::singleShot(0, this, &Socket::createSocket);
return;
}
currentFortune = nextFortune;
}
void Socket::start() {
moveToThread(&cThread);
connect(&cThread, SIGNAL(started()), this, SLOT(createSocket()));
// connect(this, SIGNAL(finished()), &cThread, SLOT(quit()));
cThread.start();
}
void Socket::displayError(QAbstractSocket::SocketError socketError)
{
switch (socketError) {
case QAbstractSocket::RemoteHostClosedError:
break;
case QAbstractSocket::HostNotFoundError:
qDebug() << "Host not found";
break;
case QAbstractSocket::ConnectionRefusedError:
qDebug() << "Connection refused";
break;
default:
qDebug() << "Error : " << tcpSocket->errorString();
}
}
QByteArray Socket::IntToArray(qint32 source) //Use qint32 to ensure that the number have 4 bytes
{
QByteArray temp;
QDataStream data(&temp, QIODevice::ReadWrite);
data << source;
return temp;
}
bool Socket::writeData(QByteArray data)
{
qDebug("send sockettttt");
if(tcpSocket->state() == QAbstractSocket::ConnectedState)
{
// tcpSocket->write(IntToArray(data.size())); //write size of data
tcpSocket->write(data); //write the data itself
// tcpSocket->write("bonjour", strlen("bonjour"));
tcpSocket->flush();
return tcpSocket->waitForBytesWritten();
}
else
return false;
}
Socket::~Socket()
{
}