CppServer  1.0.4.0
C++ Server Library
ws_server.cpp
Go to the documentation of this file.
1 
9 #include "server/ws/ws_server.h"
10 
11 namespace CppServer {
12 namespace WS {
13 
14 bool WSServer::CloseAll(int status, const void* buffer, size_t size)
15 {
16  std::scoped_lock locker(_ws_send_lock);
17 
18  PrepareSendFrame(WS_FIN | WS_CLOSE, false, buffer, size, status);
19  if (!Multicast(_ws_send_buffer.data(), _ws_send_buffer.size()))
20  return false;
21 
22  return HTTPServer::DisconnectAll();
23 }
24 
25 bool WSServer::CloseAll(int status, std::string_view text)
26 {
27  std::scoped_lock locker(_ws_send_lock);
28 
29  PrepareSendFrame(WS_FIN | WS_CLOSE, false, text.data(), text.size(), status);
30  if (!Multicast(_ws_send_buffer.data(), _ws_send_buffer.size()))
31  return false;
32 
33  return HTTPServer::DisconnectAll();
34 }
35 
36 bool WSServer::Multicast(const void* buffer, size_t size)
37 {
38  if (!IsStarted())
39  return false;
40 
41  if (size == 0)
42  return true;
43 
44  assert((buffer != nullptr) && "Pointer to the buffer should not be null!");
45  if (buffer == nullptr)
46  return false;
47 
48  std::shared_lock<std::shared_mutex> locker(_sessions_lock);
49 
50  // Multicast all WebSocket sessions
51  for (auto& session : _sessions)
52  {
53  auto ws_session = std::dynamic_pointer_cast<WSSession>(session.second);
54  if (ws_session)
55  {
56  std::scoped_lock ws_locker(ws_session->_ws_send_lock);
57 
58  if (ws_session->_ws_handshaked)
59  ws_session->SendAsync(buffer, size);
60  }
61  }
62 
63  return true;
64 }
65 
66 } // namespace WS
67 } // namespace CppServer
std::map< CppCommon::UUID, std::shared_ptr< TCPSession > > _sessions
Definition: tcp_server.h:212
std::shared_mutex _sessions_lock
Definition: tcp_server.h:211
bool IsStarted() const noexcept
Is the server started?
Definition: tcp_server.h:100
virtual bool CloseAll()
Definition: ws_server.h:41
bool Multicast(const void *buffer, size_t size) override
Multicast data to all connected WebSocket sessions.
Definition: ws_server.cpp:36
static const uint8_t WS_CLOSE
Close frame.
Definition: ws.h:39
void PrepareSendFrame(uint8_t opcode, bool mask, const void *buffer, size_t size, int status=0)
Prepare WebSocket send frame.
Definition: ws.cpp:212
static const uint8_t WS_FIN
Final frame.
Definition: ws.h:33
std::mutex _ws_send_lock
Send buffer lock.
Definition: ws.h:189
std::vector< uint8_t > _ws_send_buffer
Send buffer.
Definition: ws.h:191
C++ Server project definitions.
Definition: asio.h:56
WebSocket server definition.