-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtcpserver.cpp
More file actions
72 lines (63 loc) · 2.04 KB
/
Copy pathtcpserver.cpp
File metadata and controls
72 lines (63 loc) · 2.04 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
#include "tcpserver.h"
#include "functions.h"
#include <QCoreApplication>
#include <QDebug>
TcpServer::~TcpServer() {
foreach (int i, SClients.keys()) {
SClients[i]->close();
SClients.remove(i);
}
tcpServer->close();
server_status = 0;
}
TcpServer::TcpServer(QObject *parent) : QObject(parent) {
tcpServer = new QTcpServer(this);
connect(tcpServer, &QTcpServer::newConnection, this,
&TcpServer::slotNewConnection);
test();
if (!tcpServer->listen(QHostAddress::Any, 33333)) {
qDebug() << "Server is not started";
} else {
server_status = 1;
qDebug() << "Server is started";
}
}
void TcpServer::slotNewConnection() {
if (server_status == 1) {
QTcpSocket *clientSocket = tcpServer->nextPendingConnection();
int user_socket_id = clientSocket->socketDescriptor();
SClients[user_socket_id] = clientSocket;
connect(SClients[user_socket_id], &QTcpSocket::readyRead, this,
&TcpServer::slotServerRead);
connect(SClients[user_socket_id], &QTcpSocket::disconnected, this,
&TcpServer::slotClientDisconnected);
}
}
void TcpServer::slotServerRead() {
QTcpSocket *clientSocket = (QTcpSocket *)sender();
QByteArray array;
while (clientSocket->bytesAvailable() > 0)
array = clientSocket->readAll();
if (!array.trimmed().isEmpty()) {
QByteArray request = array.trimmed();
QByteArray encryptedReq =
parser(request); // Вызов функции parser() для обработки запроса
if (encryptedReq.toStdString().find("Error!") != std::string::npos) {
clientSocket->write(request + "\r\n");
clientSocket->write(encryptedReq + "\r\n");
} else {
clientSocket->write(request + "\r\n");
clientSocket->write(encryptedReq + "\r\n");
}
}
}
void TcpServer::slotClientDisconnected() {
QTcpSocket *clientSocket = (QTcpSocket *)sender();
int user_socket_id = clientSocket->socketDescriptor();
clientSocket->close();
SClients.remove(user_socket_id);
}
void TcpServer::close() {
this->~TcpServer();
QCoreApplication::quit();
}