serverList.cpp (1292B)
1 #include "serverList.h" 2 3 namespace bridgeClient 4 { 5 constexpr std::chrono::seconds g_expireTime(10); 6 7 ServerList::ServerList(const bridgeLib::PluginDesc& _desc) : m_udpClient(_desc, [this](const std::string& _host, const bridgeLib::ServerInfo& _serverInfo, const bridgeLib::Error& _error) 8 { 9 onServerFound(_host, _serverInfo, _error); 10 }) 11 { 12 } 13 14 std::set<ServerList::Entry> ServerList::getEntries() const 15 { 16 std::set<Entry> entries; 17 { 18 std::scoped_lock lock(m_entriesMutex); 19 entries = m_entries; 20 } 21 removeExpiredEntries(entries); 22 return entries; 23 } 24 25 void ServerList::removeExpiredEntries(std::set<Entry>& _entries) 26 { 27 for(auto it = _entries.begin(); it != _entries.end();) 28 { 29 auto& e = *it; 30 31 const auto elapsed = std::chrono::duration_cast<std::chrono::seconds>(Clock::now() - e.lastSeen); 32 33 if(elapsed >= g_expireTime) 34 it = _entries.erase(it); 35 else 36 ++it; 37 } 38 } 39 40 void ServerList::onServerFound(const std::string& _host, const bridgeLib::ServerInfo& _serverInfo, const bridgeLib::Error& _error) 41 { 42 Entry e; 43 e.serverInfo = _serverInfo; 44 e.err = _error; 45 e.host = _host; 46 e.lastSeen = std::chrono::system_clock::now(); 47 48 std::scoped_lock lock(m_entriesMutex); 49 m_entries.erase(e); 50 removeExpiredEntries(m_entries); 51 m_entries.insert(e); 52 } 53 }