Server.h 2.1 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 "Network/Session.h"
  14. #include "Util/mini.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() {};
  25. //获取Session
  26. Session::Ptr get(const string &tag);
  27. void for_each_session(const function<void(const string &id, const Session::Ptr &session)> &cb);
  28. private:
  29. SessionMap() = default;
  30. //移除Session
  31. bool del(const string &tag);
  32. //添加Session
  33. bool add(const string &tag, const Session::Ptr &session);
  34. private:
  35. mutex _mtx_session;
  36. unordered_map<string, 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);
  43. ~SessionHelper();
  44. const Session::Ptr &session() const;
  45. private:
  46. string _identifier;
  47. Session::Ptr _session;
  48. SessionMap::Ptr _session_map;
  49. std::weak_ptr<Server> _server;
  50. };
  51. //
  52. // server 基类, 暂时仅用于剥离 SessionHelper 对 TcpServer 的依赖
  53. // 后续将 TCP 与 UDP 服务通用部分加到这里.
  54. //
  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