shared_state.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. //
  2. // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // Official repository: https://github.com/vinniefalco/CppCon2018
  8. //
  9. #include "shared_state.hpp"
  10. #include "websocket_session.hpp"
  11. shared_state::
  12. shared_state(std::string doc_root)
  13. : doc_root_(std::move(doc_root))
  14. {
  15. }
  16. void
  17. shared_state::
  18. join(websocket_session* session)
  19. {
  20. std::lock_guard<std::mutex> lock(mutex_);
  21. sessions_.insert(session);
  22. }
  23. void
  24. shared_state::
  25. leave(websocket_session* session)
  26. {
  27. std::lock_guard<std::mutex> lock(mutex_);
  28. sessions_.erase(session);
  29. }
  30. // Broadcast a message to all websocket client sessions
  31. void
  32. shared_state::
  33. send(std::string message)
  34. {
  35. // Put the message in a shared pointer so we can re-use it for each client
  36. auto const ss = boost::make_shared<std::string const>(std::move(message));
  37. // Make a local list of all the weak pointers representing
  38. // the sessions, so we can do the actual sending without
  39. // holding the mutex:
  40. std::vector<boost::weak_ptr<websocket_session>> v;
  41. {
  42. std::lock_guard<std::mutex> lock(mutex_);
  43. v.reserve(sessions_.size());
  44. for(auto p : sessions_)
  45. v.emplace_back(p->weak_from_this());
  46. }
  47. // For each session in our local list, try to acquire a strong
  48. // pointer. If successful, then send the message on that session.
  49. for(auto const& wp : v)
  50. if(auto sp = wp.lock())
  51. sp->send(ss);
  52. }