RecordControlApplication/TcpServer.cpp

50 lines
1.5 KiB
C++
Raw Normal View History

2024-01-18 15:41:43 +08:00
#include "TcpServer.h"
2024-03-04 16:22:40 +08:00
#include "Log.h"
2024-01-18 15:41:43 +08:00
#include <QTcpSocket>
TcpServer::TcpServer(QObject* parent)
: QTcpServer(parent)
{
controller = new TcpController();
connect(this, &TcpServer::newConnection, this, &TcpServer::onNewConnect);
}
/**
2024-03-04 16:22:40 +08:00
* @brief
2024-01-18 15:41:43 +08:00
*/
void TcpServer::onNewConnect()
{
if (this->hasPendingConnections()) {
QTcpSocket* socket = this->nextPendingConnection();
2024-03-04 16:22:40 +08:00
Log::info("new client connected, ip: {}", socket->peerAddress().toString().toStdString());
2024-01-18 15:41:43 +08:00
clients.push_back(socket);
connect(socket, &QTcpSocket::readyRead, this, &TcpServer::onReadyRead);
connect(socket, &QTcpSocket::disconnected, [=] {
QTcpSocket* sk = static_cast<QTcpSocket*>(sender());
2024-03-04 16:22:40 +08:00
Log::info(" one client disconnect...");
2024-01-18 15:41:43 +08:00
clients.removeOne(sk);
});
}
}
/**
2024-03-04 16:22:40 +08:00
* @brief
2024-01-18 15:41:43 +08:00
*/
void TcpServer::onReadyRead()
{
QTcpSocket* socket = static_cast<QTcpSocket*>(sender());
// url=xxx
QString data = socket->readLine().trimmed();
if (data.contains("=")) {
QString url = data.split("=")[1];
bool contains = controller->getRoutes().contains(url);
if (contains) {
2024-03-04 16:22:40 +08:00
Log::info("tcp server receive request: {}", url.toStdString());
auto handler = controller->getRoutes().value(url);
handler(socket);
} else {
socket->write(QString("url=%1\r\nstatus=error").arg(url).toStdString().data());
}
2024-01-18 15:41:43 +08:00
}
}