1 Star 0 Fork 0

harrishp/SimpleAsioServer

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
Server.hpp 2.00 KB
一键复制 编辑 原始数据 按行查看 历史
Harrishanpan 提交于 2023-10-18 09:12 . 添加项目文件。
#pragma once
#include <boost/asio/buffer.hpp>
#include <unordered_map>
#include <numeric>
#include "RWHandler.hpp"
const int MaxConnectionNum = 65536;
const int MaxRecvSize = 65536;
class Server {
public:
Server(io_service& ios, short port):m_ios(ios),m_acceptor(ios,tcp::endpoint(tcp::v4(),port)),m_connIdPool(MaxConnectionNum) {
m_connIdPool.resize(MaxConnectionNum);
std::iota(m_connIdPool.begin(), m_connIdPool.end(), 1);
}
~Server(){}
void Accept() {
cout << "Start Listening " << endl;
std::shared_ptr<RWHandler> handler = CreateHandler();
m_acceptor.async_accept(handler->GetSocket(), [this, handler](const boost::system::error_code& ec) {
if (ec) {
cout << ec.value() << " " << ec.message() << endl;
HandleAcpError(handler, ec);
return;
}
m_handlers.insert(std::make_pair(handler->GetConnId(), handler));
cout << "Current connect count: " << m_handlers.size() << endl;
handler->HandleRead();
Accept();
});
}
private:
void HandleAcpError(std::shared_ptr<RWHandler> eventHandler, const boost::system::error_code& ec) {
cout << "Erroe, error reason:" << ec.value() << ec.message() << endl;
// 关闭socket,移除读/写事件处理器
eventHandler->CloseSocket();
StopAccept();
}
void StopAccept() {
boost::system::error_code ec;
m_acceptor.cancel(ec);
m_acceptor.close(ec);
m_ios.stop();
}
std::shared_ptr<RWHandler> CreateHandler() {
int connId = m_connIdPool.front();
m_connIdPool.pop_front();
std::shared_ptr<RWHandler> handler = std::make_shared<RWHandler>(m_ios);
handler->SetConnId(connId);
handler->SetCallBackError([this](int connId) {
RecyclConnId(connId);
});
return handler;
}
void RecyclConnId(int connId){
auto it = m_handlers.find(connId);
if (it != m_handlers.end())
m_handlers.erase(it);
cout << "current connect count:" << m_handlers.size() << endl;
m_connIdPool.push_back(connId);
}
private:
io_service& m_ios;
tcp::acceptor m_acceptor;
std::unordered_map<int, std::shared_ptr<RWHandler>> m_handlers;
list<int> m_connIdPool;
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/harrishp/simple-asio-server.git
git@gitee.com:harrishp/simple-asio-server.git
harrishp
simple-asio-server
SimpleAsioServer
master

搜索帮助