Session.h
Server.h
Session
session有什么
- async 对应poller的异步
- send对应socket的发送
- has a sock
继承session的需要实现
virtual void onRecv(const Buffer::Ptr &buf) = 0;
virtual void onError(const SockException &err) = 0;
virtual void onManager() = 0;//每隔一段时间触发, 用来做超时管理
virtual void attachServer(const Server &server) {}//在创建 Session 后, Server 会把自身的配置参数通过该函数传递给 Session
session自身的获取id+安全关闭
string Session::getIdentifier() const {
if (_id.empty()) {
_id = to_string(++s_session_index) + '-' + to_string(getSock()->rawFD());
}
return _id;
}
void Session::safeShutdown(const SockException &ex) {
std::weak_ptr<Session> weakSelf = shared_from_this();
async_first([weakSelf,ex](){
auto strongSelf = weakSelf.lock();
if (strongSelf) {
strongSelf->shutdown(ex);//sock自己关闭
}
});
}
SessionMap
存放的是session的弱指针
// 全局的 Session 记录对象, 方便后面管理
// 线程安全的
class SessionMap : public std::enable_shared_from_this<SessionMap> {
public:
friend class SessionHelper;
using Ptr = std::shared_ptr<SessionMap>;
//单例
static SessionMap &Instance();
~SessionMap() = default;
//获取Session
Session::Ptr get(const std::string &tag);
void for_each_session(const std::function<void(const std::string &id, const Session::Ptr &session)> &cb);
private:
SessionMap() = default;
//移除Session
bool del(const std::string &tag);
//添加Session
bool add(const std::string &tag, const Session::Ptr &session);
private:
std::mutex _mtx_session;
std::unordered_map<std::string, std::weak_ptr<Session> > _map_session;
};