|
11 | 11 | #ifndef TOOLKIT_NETWORK_UDPSERVER_H |
12 | 12 | #define TOOLKIT_NETWORK_UDPSERVER_H |
13 | 13 |
|
| 14 | +#if __cplusplus >= 201703L |
| 15 | +#include <array> |
| 16 | +#include <string_view> |
| 17 | +#endif |
14 | 18 | #include "Server.h" |
15 | 19 | #include "Session.h" |
16 | 20 |
|
17 | 21 | namespace toolkit { |
18 | 22 |
|
19 | 23 | class UdpServer : public Server { |
20 | 24 | public: |
| 25 | +#if __cplusplus >= 201703L |
| 26 | + class PeerIdType : public std::array<char, 18> { |
| 27 | +#else |
| 28 | + class PeerIdType : public std::string { |
| 29 | +#endif |
| 30 | + public: |
| 31 | +#if __cplusplus < 201703L |
| 32 | + PeerIdType() { |
| 33 | + resize(18); |
| 34 | + } |
| 35 | +#endif |
| 36 | + bool operator==(const PeerIdType &that) const { |
| 37 | + return as<uint64_t>(0) == that.as<uint64_t>(0) && |
| 38 | + as<uint64_t>(8) == that.as<uint64_t>(8) && |
| 39 | + as<uint16_t>(16) == that.as<uint16_t>(16); |
| 40 | + } |
| 41 | + |
| 42 | + private: |
| 43 | + template <class T> |
| 44 | + const T& as(size_t offset) const { |
| 45 | + return *(reinterpret_cast<const T *>(data() + offset)); |
| 46 | + } |
| 47 | + }; |
| 48 | + |
21 | 49 | using Ptr = std::shared_ptr<UdpServer>; |
22 | | - using PeerIdType = std::string; |
23 | 50 | using onCreateSocket = std::function<Socket::Ptr(const EventPoller::Ptr &, const Buffer::Ptr &, struct sockaddr *, int)>; |
24 | 51 |
|
25 | 52 | explicit UdpServer(const EventPoller::Ptr &poller = nullptr); |
@@ -75,6 +102,15 @@ class UdpServer : public Server { |
75 | 102 | virtual void cloneFrom(const UdpServer &that); |
76 | 103 |
|
77 | 104 | private: |
| 105 | + struct PeerIdHash { |
| 106 | +#if __cplusplus >= 201703L |
| 107 | + size_t operator()(const PeerIdType &v) const noexcept { return std::hash<std::string_view> {}(std::string_view(v.data(), v.size())); } |
| 108 | +#else |
| 109 | + size_t operator()(const PeerIdType &v) const noexcept { return std::hash<std::string> {}(v); } |
| 110 | +#endif |
| 111 | + }; |
| 112 | + using SessionMapType = std::unordered_map<PeerIdType, SessionHelper::Ptr, PeerIdHash>; |
| 113 | + |
78 | 114 | /** |
79 | 115 | * @brief 开始udp server |
80 | 116 | * @param port 本机端口,0则随机 |
@@ -150,7 +186,7 @@ class UdpServer : public Server { |
150 | 186 | //cloned server共享主server的session map,防止数据在不同server间漂移 [AUTO-TRANSLATED:9a149e52] |
151 | 187 | //Cloned server shares the session map with the main server, preventing data drift between different servers |
152 | 188 | std::shared_ptr<std::recursive_mutex> _session_mutex; |
153 | | - std::shared_ptr<std::unordered_map<PeerIdType, SessionHelper::Ptr> > _session_map; |
| 189 | + std::shared_ptr<SessionMapType> _session_map; |
154 | 190 | //主server持有cloned server的引用 [AUTO-TRANSLATED:04a6403a] |
155 | 191 | //Main server holds a reference to the cloned server |
156 | 192 | std::unordered_map<EventPoller *, Ptr> _cloned_server; |
|
0 commit comments