Server.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * Copyright (c) 2021 The ZLToolKit project authors. All Rights Reserved.
  3. *
  4. * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
  5. *
  6. * Use of this source code is governed by MIT license that can be found in the
  7. * LICENSE file in the root of the source tree. All contributing project authors
  8. * may be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef ZLTOOLKIT_SERVER_H
  11. #define ZLTOOLKIT_SERVER_H
  12. #include <unordered_map>
  13. #include "Util/mini.h"
  14. #include "Session.h"
  15. namespace toolkit {
  16. // 全局的 Session 记录对象, 方便后面管理
  17. // 线程安全的
  18. class SessionMap : public std::enable_shared_from_this<SessionMap> {
  19. public:
  20. friend class SessionHelper;
  21. using Ptr = std::shared_ptr<SessionMap>;
  22. //单例
  23. static SessionMap &Instance();
  24. ~SessionMap() = default;
  25. //获取Session
  26. Session::Ptr get(const std::string &tag);
  27. void for_each_session(const std::function<void(const std::string &id, const Session::Ptr &session)> &cb);
  28. private:
  29. SessionMap() = default;
  30. //移除Session
  31. bool del(const std::string &tag);
  32. //添加Session
  33. bool add(const std::string &tag, const Session::Ptr &session);
  34. private:
  35. std::mutex _mtx_session;
  36. std::unordered_map<std::string, std::weak_ptr<Session> > _map_session;
  37. };
  38. class Server;
  39. class SessionHelper {
  40. public:
  41. using Ptr = std::shared_ptr<SessionHelper>;
  42. SessionHelper(const std::weak_ptr<Server> &server, Session::Ptr session, std::string cls);
  43. ~SessionHelper();
  44. const Session::Ptr &session() const;
  45. const std::string &className() const;
  46. private:
  47. std::string _cls;
  48. std::string _identifier;
  49. Session::Ptr _session;
  50. SessionMap::Ptr _session_map;
  51. std::weak_ptr<Server> _server;
  52. };
  53. // server 基类, 暂时仅用于剥离 SessionHelper 对 TcpServer 的依赖
  54. // 后续将 TCP 与 UDP 服务通用部分加到这里.
  55. class Server : public std::enable_shared_from_this<Server>, public mINI {
  56. public:
  57. using Ptr = std::shared_ptr<Server>;
  58. explicit Server(EventPoller::Ptr poller = nullptr);
  59. virtual ~Server() = default;
  60. protected:
  61. EventPoller::Ptr _poller;
  62. };
  63. } // namespace toolkit
  64. #endif // ZLTOOLKIT_SERVER_H