forked from ts-way/PassiveNetwork
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcpreceiver.cpp
92 lines (80 loc) · 1.64 KB
/
tcpreceiver.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
#include "tcpreceiver.h"
TCPReceiver::TCPReceiver(QObject *parent) :
QObject(parent)
{
port = 4444;
client = new QTcpSocket();
connect(client, SIGNAL(connected()), this, SLOT(newConnection()));
connect(client, SIGNAL(disconnected()), this, SLOT(endConnection()), Qt::QueuedConnection);
connect(client, SIGNAL(readyRead()), this, SLOT(clientReadString()), Qt::QueuedConnection);
}
/**
* Set port to listen on
*/
void TCPReceiver::setPort(quint16 _port)
{
port = _port;
}
/**
* Set remote host
*/
void TCPReceiver::setHost(QString _host)
{
host = _host;
}
/**
* Start the connection with the remote host
*/
void TCPReceiver::start()
{
stop();
client->connectToHost(host, port);
}
/**
* Stop the connection
*/
void TCPReceiver::stop()
{
if (client->state() != QAbstractSocket::UnconnectedState) {
client->disconnectFromHost();
if (client->state() != QAbstractSocket::UnconnectedState) {
client->waitForDisconnected();
}
}
}
/**
* Set up the client tcp socket for an incoming connection
*/
void TCPReceiver::newConnection()
{
emit connectionReady();
}
/**
* Disconnect client connection
*/
void TCPReceiver::endConnection()
{
emit connectionNotReady();
}
/**
* Send the string to the client
*/
void TCPReceiver::clientWriteString(QByteArray buffer)
{
if (client) {
client->write(buffer);
}
}
/**
* Receive a string from the client
*/
QByteArray TCPReceiver::clientReadString()
{
if (client) {
QByteArray buffer = client->read(1024*1024);
emit stringRead(buffer);
return buffer;
} else {
return "";
}
}