#include "TcpServer.h" #include "Log.h" #include TcpServer::TcpServer(QObject* parent) : QTcpServer(parent) { handler = new TcpRequestHandler(); connect(this, &TcpServer::newConnection, this, &TcpServer::onNewConnect); } TcpServer::~TcpServer() { delete handler; if (!clients.isEmpty()) { qDeleteAll(clients); clients.clear(); } } /** * @brief 监听端口 */ void TcpServer::listen() { bool ret = QTcpServer::listen(QHostAddress::Any, 8080); if (!ret) { Log::error(QString("listen port 8080 failed, %1").arg(errorString()).toStdString()); return; } else { Log::info("start tcp server, listen port 8080"); } } /** * @brief 关闭tcp服务器 */ void TcpServer::close() { QTcpServer::close(); if (!clients.isEmpty()) { qDeleteAll(clients); clients.clear(); } } /** * @brief 服务器有新的连接 */ void TcpServer::onNewConnect() { if (this->hasPendingConnections()) { QTcpSocket* socket = this->nextPendingConnection(); Log::info("new client connected, ip: {}", socket->peerAddress().toString().toStdString()); TcpConnectionHandler* connection = new TcpConnectionHandler(socket, handler); clients.push_back(connection); connect(connection, &TcpConnectionHandler::disconnected, [=] { // 从列表中移除该指针 TcpConnectionHandler* conn = static_cast(sender()); clients.removeOne(conn); }); } }