31 lines
1.0 KiB
C++
31 lines
1.0 KiB
C++
#include "ChatRoom.h"
|
|
#include "WebSocketChatSession.h"
|
|
|
|
void ChatRoom::join(WebSocketSession *session) {
|
|
std::lock_guard<std::mutex> lock(m_mutex);
|
|
m_sessions.insert(session);
|
|
}
|
|
|
|
void ChatRoom::leave(WebSocketSession *session) {
|
|
std::lock_guard<std::mutex> lock(m_mutex);
|
|
m_sessions.erase(session);
|
|
}
|
|
|
|
void ChatRoom::send(std::string message) {
|
|
auto const ss = std::make_shared<std::string const>(std::move(message));
|
|
|
|
// Make a local list of all the weak pointers representing
|
|
// the sessions, so we can do the actual sending without
|
|
// holding the mutex:
|
|
std::vector<std::weak_ptr<WebSocketSession>> v;
|
|
{
|
|
std::lock_guard<std::mutex> lock(m_mutex);
|
|
v.reserve(m_sessions.size());
|
|
for (auto p : m_sessions) v.emplace_back(p->weak_from_this());
|
|
}
|
|
|
|
// For each session in our local list, try to acquire a strong
|
|
// pointer. If successful, then send the message on that session.
|
|
for (auto const &wp : v)
|
|
if (auto sp = wp.lock()) sp->send(ss);
|
|
} |