forked from ts-way/PassiveNetwork
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcpserverthread.cpp
93 lines (80 loc) · 1.72 KB
/
tcpserverthread.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
#include "tcpserverthread.h"
TCPServerThread::TCPServerThread(QObject *parent) :
QObject(parent)
{
port = 4444;
client = NULL;
server.setMaxPendingConnections(1);
connect(&server, SIGNAL(newConnection()), this, SLOT(newConnection()), Qt::QueuedConnection);
}
/**
* Set port to listen on
*/
void TCPServerThread::setPort(quint16 _port)
{
port = _port;
}
/**
* Start the server and wait for connections
*/
void TCPServerThread::start()
{
// listen on all addresses
server.listen(QHostAddress::Any, port);
if (!server.isListening()) {
emit connectionError(server.errorString());
return;
}
}
/**
* Stop the server and the connections
*/
void TCPServerThread::stop()
{
server.close();
endConnection();
}
/**
* Set up the client tcp socket for an incoming connection
*/
void TCPServerThread::newConnection()
{
if (client) {
endConnection();
}
client = server.nextPendingConnection();
connect(client, SIGNAL(disconnected()), client, SLOT(deleteLater()), Qt::QueuedConnection);
connect(client, SIGNAL(readyRead()), this, SLOT(clientReadString()), Qt::QueuedConnection);
}
/**
* Disconnect client connection
*/
void TCPServerThread::endConnection()
{
if (client) {
client->disconnectFromHost();
client = NULL;
}
}
/**
* Send the string to the client
*/
void TCPServerThread::clientWriteString(QString buffer)
{
if (client) {
client->write(buffer.toAscii());
}
}
/**
* Receive a string from the client
*/
QString TCPServerThread::clientReadString()
{
if (client) {
QString string(client->read(1024*1024));
emit stringRead(string);
return string;
} else {
return "";
}
}