RecordControlApplication/TcpServer.cpp
2024-01-17 23:41:43 -08:00

43 lines
1.2 KiB
C++

#include "TcpServer.h"
#include <QTcpSocket>
TcpServer::TcpServer(QObject* parent)
: QTcpServer(parent)
{
controller = new TcpController();
connect(this, &TcpServer::newConnection, this, &TcpServer::onNewConnect);
}
/**
* @brief new connection slots
*/
void TcpServer::onNewConnect()
{
if (this->hasPendingConnections()) {
QTcpSocket* socket = this->nextPendingConnection();
clients.push_back(socket);
connect(socket, &QTcpSocket::readyRead, this, &TcpServer::onReadyRead);
connect(socket, &QTcpSocket::disconnected, [=] {
QTcpSocket* sk = static_cast<QTcpSocket*>(sender());
qDebug() << "clients " << sk << "disconnected";
clients.removeOne(sk);
});
}
}
/**
* @brief receive data from clients
*/
void TcpServer::onReadyRead()
{
QTcpSocket* socket = static_cast<QTcpSocket*>(sender());
QString url = socket->readLine().trimmed();
bool contains = controller->getRoutes().contains(url);
if (contains) {
auto handler = controller->getRoutes().value(url);
handler(socket);
} else {
socket->write("error: request url not found");
}
}