RecordControlApplication/TcpServer.cpp

47 lines
1.3 KiB
C++
Raw Normal View History

2024-01-18 15:41:43 +08:00
#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() << "client " << sk << "disconnected";
2024-01-18 15:41:43 +08:00
clients.removeOne(sk);
});
}
}
/**
* @brief receive data from clients
*/
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) {
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
}
}