RecordControlApplication/TcpServer.cpp

66 lines
1.5 KiB
C++
Raw Permalink 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)
{
handler = new TcpRequestHandler();
2024-01-18 15:41:43 +08:00
connect(this, &TcpServer::newConnection, this, &TcpServer::onNewConnect);
}
TcpServer::~TcpServer()
{
delete handler;
if (!clients.isEmpty()) {
qDeleteAll(clients);
clients.clear();
}
}
2024-01-18 15:41:43 +08:00
/**
* @brief
2024-01-18 15:41:43 +08:00
*/
void TcpServer::listen()
2024-01-18 15:41:43 +08:00
{
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();
2024-01-18 15:41:43 +08:00
}
}
/**
* @brief
2024-01-18 15:41:43 +08:00
*/
void TcpServer::onNewConnect()
2024-01-18 15:41:43 +08:00
{
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<TcpConnectionHandler*>(sender());
clients.removeOne(conn);
});
2024-01-18 15:41:43 +08:00
}
}