Loading...
Searching...
No Matches
ml::WebSocketProvider Class Reference

WebSocket connection with automatic JSON dispatch. More...

#include <Malena/Providers/WebSocketProvider.h>

Inheritance diagram for ml::WebSocketProvider:
[legend]

Public Member Functions

 WebSocketProvider (const std::string &keyField="type")
void connect (const std::string &url)
 Open a WebSocket connection to url.
void disconnect ()
 Close the connection gracefully.
void dispatch (const json &msg)
 Dispatch a JSON object to the matching subscriber.
void offAllMessages ()
 Unsubscribe from all messages registered by this object.
template<typename DataType, typename Enum>
void offMessage (Enum event)
 Unsubscribe from a specific typed message.
void on (const std::string &value, std::function< void(const json &)> callback)
 Subscribe a callback for a specific message value.
void onClose (std::function< void(int, const std::string &)> callback)
 Called on the main thread when the connection closes.
void onError (std::function< void(const std::string &)> callback)
 Called on the main thread on a protocol or network error.
template<typename DataType, typename Enum>
void onMessage (Enum event, std::function< void(const DataType &)> callback)
 Register a callback to receive a typed message.
void onOpen (std::function< void()> callback)
 Called on the main thread when the connection opens.
void send (const json &msg)
 Send a JSON object as a UTF-8 text frame.
void send (const std::string &text)
 Send a raw text frame.
template<typename DataType, typename Enum>
void sendMessage (Enum event, const DataType &data)
 Publish a typed message to all current subscribers.
void setMaxReconnectAttempts (int n)
 Maximum reconnect attempts. Pass -1 for unlimited.
void setReconnectDelay (int seconds)
 Delay in seconds before reconnecting after an unexpected close.

Detailed Description

WebSocket connection with automatic JSON dispatch.

WebSocketProvider combines a WebSocketClient (raw transport) with a NetworkDispatcher (typed routing) into a single reusable object.

Create one in your application class, call on() in each hook's init() to declare which message types it cares about, then call connect() once to open the connection:

// In your application constructor:
_network.onOpen([this]{
_network.send({{"type","register"}, {"role","admin"}});
});
_network.connect("ws://localhost:3000");
_chatHook->init(_network);
_studentsHook->init(_network);
// In a hook's init():
void ChatHook::init(ml::WebSocketProvider& network)
{
network.on("student_message", [this](const ml::json& msg) {
handleStudentMessage(msg["from"], msg["text"], msg.value("ts", ""));
});
sendHook(AppShell::Hook::GRAPHIC);
}
void on(const std::string &value, std::function< void(const json &)> callback)
Subscribe a callback for a specific message value.
WebSocket connection with automatic JSON dispatch.
nlohmann::json json
Alias for nlohmann::json.
Definition Json.h:32
See also
NetworkDispatcher, WebSocketClient

Definition at line 51 of file WebSocketProvider.h.

Constructor & Destructor Documentation

◆ WebSocketProvider()

ml::WebSocketProvider::WebSocketProvider ( const std::string & keyField = "type")
explicit

Member Function Documentation

◆ connect()

void ml::WebSocketProvider::connect ( const std::string & url)

Open a WebSocket connection to url.

Automatically parses every incoming text frame as JSON and dispatches it to subscribers registered with on(). Non-JSON frames are silently ignored.

Parameters
urlws:// or wss:// URL.

◆ disconnect()

void ml::WebSocketProvider::disconnect ( )

Close the connection gracefully.

◆ dispatch()

void ml::NetworkDispatcher::dispatch ( const json & msg)
inherited

Dispatch a JSON object to the matching subscriber.

Reads _keyField from the message and publishes its value on the message bus. No-op if the field is missing or empty.

Parameters
msgParsed JSON message from the network.

◆ offAllMessages()

void ml::Messenger::offAllMessages ( )
inherited

Unsubscribe from all messages registered by this object.

Called automatically by the destructor. Only call manually if you need to reset all subscriptions while the object is still alive.

◆ offMessage()

template<typename DataType, typename Enum>
void ml::Messenger::offMessage ( Enum event)
inherited

Unsubscribe from a specific typed message.

After this call, the callback previously registered for event and DataType will no longer be invoked. Safe to call from within the callback itself.

Template Parameters
DataTypeThe payload type of the subscription to remove.
EnumThe enum type identifying the event.
Parameters
eventThe specific event to unsubscribe from.

◆ on()

void ml::NetworkDispatcher::on ( const std::string & value,
std::function< void(const json &)> callback )
inherited

Subscribe a callback for a specific message value.

Parameters
valueThe value of the key field to listen for.
callbackCalled with the full JSON object when the value matches.

◆ onClose()

void ml::WebSocketProvider::onClose ( std::function< void(int, const std::string &)> callback)

Called on the main thread when the connection closes.

◆ onError()

void ml::WebSocketProvider::onError ( std::function< void(const std::string &)> callback)

Called on the main thread on a protocol or network error.

◆ onMessage()

template<typename DataType, typename Enum>
void ml::Messenger::onMessage ( Enum event,
std::function< void(const DataType &)> callback )
inherited

Register a callback to receive a typed message.

The callback is invoked each time sendMessage is called with the same event and DataType. Multiple calls with the same event replace the previous callback for that event.

Template Parameters
DataTypeThe expected payload type.
EnumThe enum type identifying the event.
Parameters
eventThe specific event to listen for.
callbackFunction called with a const reference to the payload when the event fires.

◆ onOpen()

void ml::WebSocketProvider::onOpen ( std::function< void()> callback)

Called on the main thread when the connection opens.

◆ send() [1/2]

void ml::WebSocketProvider::send ( const json & msg)

Send a JSON object as a UTF-8 text frame.

◆ send() [2/2]

void ml::WebSocketProvider::send ( const std::string & text)

Send a raw text frame.

◆ sendMessage()

template<typename DataType, typename Enum>
void ml::Messenger::sendMessage ( Enum event,
const DataType & data )
inherited

Publish a typed message to all current subscribers.

All objects that have called onMessage for the same event and DataType will have their callbacks invoked with data. Delivery is immediate unless MessageManager is currently iterating, in which case it is deferred.

Template Parameters
DataTypeThe payload type. Must match the type used in the corresponding onMessage call.
EnumThe enum type identifying the event.
Parameters
eventThe specific event to send.
dataThe payload to deliver to subscribers.

◆ setMaxReconnectAttempts()

void ml::WebSocketProvider::setMaxReconnectAttempts ( int n)

Maximum reconnect attempts. Pass -1 for unlimited.

◆ setReconnectDelay()

void ml::WebSocketProvider::setReconnectDelay ( int seconds)

Delay in seconds before reconnecting after an unexpected close.


The documentation for this class was generated from the following file: