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)
|
|
|
|
{
|
2024-05-07 15:06:36 +08:00
|
|
|
handler = new TcpRequestHandler();
|
|
|
|
|
2024-01-18 15:41:43 +08:00
|
|
|
connect(this, &TcpServer::newConnection, this, &TcpServer::onNewConnect);
|
|
|
|
}
|
|
|
|
|
2024-05-07 15:06:36 +08:00
|
|
|
TcpServer::~TcpServer()
|
|
|
|
{
|
|
|
|
delete handler;
|
|
|
|
if (!clients.isEmpty()) {
|
|
|
|
qDeleteAll(clients);
|
|
|
|
clients.clear();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-18 15:41:43 +08:00
|
|
|
/**
|
2024-05-07 15:06:36 +08:00
|
|
|
* @brief 监听端口
|
2024-01-18 15:41:43 +08:00
|
|
|
*/
|
2024-05-07 15:06:36 +08:00
|
|
|
void TcpServer::listen()
|
2024-01-18 15:41:43 +08:00
|
|
|
{
|
2024-05-07 15:06:36 +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
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2024-05-07 15:06:36 +08:00
|
|
|
* @brief 服务器有新的连接
|
2024-01-18 15:41:43 +08:00
|
|
|
*/
|
2024-05-07 15:06:36 +08:00
|
|
|
void TcpServer::onNewConnect()
|
2024-01-18 15:41:43 +08:00
|
|
|
{
|
2024-05-07 15:06:36 +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
|
|
|
}
|
|
|
|
}
|