zlMediaKit 6 session模块

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;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值