#include "TcpServer.h" #include "Log.h" #include TcpServer::TcpServer(QObject* parent) : QTcpServer(parent) { controller = new TcpController(); connect(this, &TcpServer::newConnection, this, &TcpServer::onNewConnect); } /** * @brief 服务器有新的连接 */ void TcpServer::onNewConnect() { if (this->hasPendingConnections()) { QTcpSocket* socket = this->nextPendingConnection(); Log::info("new client connected, ip: {}", socket->peerAddress().toString().toStdString()); clients.push_back(socket); connect(socket, &QTcpSocket::readyRead, this, &TcpServer::onReadyRead); connect(socket, &QTcpSocket::disconnected, [=] { QTcpSocket* sk = static_cast(sender()); Log::info(" one client disconnect..."); clients.removeOne(sk); }); } } /** * @brief 从缓冲区读取数据 */ 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) { 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()); } } }