代码拉取完成,页面将自动刷新
#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;
};
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。