-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcpserver.cpp
99 lines (79 loc) · 2.42 KB
/
tcpserver.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
97
98
99
#include "tcpserver.h"
#include "logcategories.h"
tcpServer::tcpServer(QObject* parent) : QTcpServer(parent)
{
}
tcpServer::~tcpServer()
{
qInfo(logTcpServer()) << "closing tcpServer";
}
int tcpServer::startServer(qint16 port) {
if (!this->listen(QHostAddress::Any, port)) {
qInfo(logTcpServer()) << "could not start on port " << port;
return -1;
}
else
{
qInfo(logTcpServer()) << "started on port " << port;
}
return 0;
}
void tcpServer::incomingConnection(qintptr socket) {
tcpServerClient* client = new tcpServerClient(socket, this);
connect(this, SIGNAL(onStopped()), client, SLOT(closeSocket()));
emit newClient(socket); // Signal par
}
void tcpServer::stopServer()
{
qInfo(logTcpServer()) << "stopping server";
emit onStopped();
}
void tcpServer::receiveDataFromClient(QByteArray data)
{
emit receiveData(data);
}
void tcpServer::sendData(QByteArray data) {
emit sendDataToClient(data);
}
tcpServerClient::tcpServerClient(int socketId, tcpServer* parent) : QObject(parent)
{
sessionId = socketId;
socket = new QTcpSocket(this);
this->parent = parent;
if (!socket->setSocketDescriptor(sessionId))
{
qInfo(logTcpServer()) << " error binding socket: " << sessionId;
return;
}
connect(socket, SIGNAL(readyRead()), this, SLOT(socketReadyRead()), Qt::DirectConnection);
connect(socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()), Qt::DirectConnection);
connect(parent, SIGNAL(sendDataToClient(QByteArray)), this, SLOT(receiveDataToClient(QByteArray)), Qt::DirectConnection);
connect(this, SIGNAL(sendDataFromClient(QByteArray)), parent, SLOT(receiveDataFromClient(QByteArray)), Qt::DirectConnection);
qInfo(logTcpServer()) << " session connected: " << sessionId;
}
void tcpServerClient::socketReadyRead() {
QByteArray data;
if (socket->bytesAvailable()) {
data=socket->readAll();
emit sendDataFromClient(data);
}
}
void tcpServerClient::socketDisconnected() {
qInfo(logTcpServer()) << sessionId << "disconnected";
socket->deleteLater();
this->deleteLater();
}
void tcpServerClient::closeSocket()
{
socket->close();
}
void tcpServerClient::receiveDataToClient(QByteArray data) {
if (socket != Q_NULLPTR && socket->isValid() && socket->isOpen())
{
socket->write(data);
}
else
{
qInfo(logTcpServer()) << "socket not open!";
}
}