#include "TcpServer.h" #include 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(sender()); qDebug() << "client " << sk << "disconnected"; clients.removeOne(sk); }); } } /** * @brief receive data from clients */ void TcpServer::onReadyRead() { QTcpSocket* socket = static_cast(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()); } } }