1 Star 0 Fork 0

Aurora/Linux

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
TcpServer.hpp 1.83 KB
一键复制 编辑 原始数据 按行查看 历史
Aurora 提交于 2025-07-13 00:44 +08:00 . 完整版httpserver
#pragma once
#include <iostream>
#include <memory>
#include <functional>
#include <sys/wait.h>
#include "Socket.hpp"
namespace TcpServerModule
{
using namespace SocketModule;
using namespace LogModule;
using tcphandler_t = std::function<bool(SockPtr, InetAddr)>;
// 它只负责进行IO,流失的IO,不对协议进行任何处理
class TcpServer
{
public:
TcpServer(int port)
: _listensockp(std::make_unique<TcpSocket>())
, _running(false)
, _port(port)
{
}
void InitServer(tcphandler_t handler)
{
_handler = handler;
_listensockp->BulidTcpSocketMethod(_port);
}
void Loop()
{
_running = true;
while (_running)
{
// 1.Accept
InetAddr clientaddr;
auto sockfd = _listensockp->Accepter(&clientaddr);
if (sockfd == nullptr)
continue;
// 2.IO处理
LOG(LogLevel::DEBUG) << "get a new client,info is : " << clientaddr.Addr();
// sockfd->Recv();
// sockfd->Send();
pid_t id = fork();
if (id == 0)
{
_listensockp->Close();
if (fork() > 0)
exit(0);
_handler(sockfd,clientaddr);
exit(0);
}
sockfd->Close();
waitpid(id, nullptr, 0);
}
_running = false;
}
~TcpServer()
{
_listensockp->Close();
}
private:
// 一定要有一个Listensock
std::unique_ptr<Socket> _listensockp;
bool _running;
tcphandler_t _handler;
int _port;
};
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/Axurea/linux.git
git@gitee.com:Axurea/linux.git
Axurea
linux
Linux
master

搜索帮助