Hi Everyone,
I have an immediate requirement.
I need to write a WebSocket server which sends messages to multiple clients connections at specific intervals like every 5 seconds or 10 seconds after each client connect.
For Example:
If Client A connects at 00:05:30 -> It should receive next messages at 00:05:35, 00:05:40, 00:05:45, 00:05:50 and so.... until disconnects
If Client B connects at 00:05:33 -> It should receive next messages at 00:05:38, 00:05:43, 00:05:48 00:05:53 and so.... until disconnects
If Client C connects at 00:05:41 -> It should receive next messages at 00:05:46, 00:05:51, 00:05:56 00:06:01 and so.... until disconnects
I am unable to think any logic managing to send the same message to each client at the different time automatically considering we need to support for 100K client connections. My class design as below.
#include "websocketpp/server.hpp"
#include "websocketpp/config/asio_no_tls.hpp"
class WebsocketServer {
public:
bool init();
void run();
void stop();
bool sendClose(string id);
bool sendData(string id, string data);
void processMessage();
private:
bool getWebsocket(const string &id, websocketpp::connection_hdl &hdl);
websocketpp::server<websocketpp::config::asio> server;
map<string, websocketpp::connection_hdl> websockets;
LogStream ls;
ostream os;
// callbacks
bool on_validate(websocketpp::connection_hdl hdl);
void on_fail(websocketpp::connection_hdl hdl);
void on_close(websocketpp::connection_hdl hdl);
};
void process_messages() {
while (1) {
unique_lock<mutex> lock(m_action_lock);
while (m_actions.empty()) {
m_action_cond.wait(lock);
}
action a = m_actions.front();
m_actions.pop();
lock.unlock();
if (a.type == SUBSCRIBE) {
unique_lock<mutex> lock(m_connection_lock);
m_connections.insert(a.hdl);
}
else if (a.type == UNSUBSCRIBE) {
unique_lock<mutex> lock(m_connection_lock);
m_connections.erase(a.hdl);
}
else if (a.type == MESSAGE) {
unique_lock<mutex> lock(m_connection_lock);
con_list::iterator it;
for (it = m_connections.begin(); it != m_connections.end(); ++it) {
m_server.send(*it, a.msg);
}
}
else {
// undefined.
}
}
}