sioxx API Reference#

The API is centered on sioxx::client, which owns the Engine.IO connection, and sioxx::socket, which represents one Socket.IO namespace.

Client#

Configure a client with sioxx::client_options, obtain namespace sockets with sioxx::client::socket(), and then connect to the server.

enum class sioxx::parser_kind#

Select the wire‑protocol parser used for Socket.IO packets.

  • json – classic text‑based protocol compatible with the reference socket.io-parser.

  • msgpack – binary protocol that uses MessagePack via nlohmann::json::to_msgpack/from_msgpack.

Values:

enumerator json#

Text protocol (default)

enumerator msgpack#

Binary MessagePack protocol.

struct client_options#

All tunable settings for a sioxx::client.

The struct uses public data members with sensible defaults.

Note

When parser_factory is provided it takes precedence over the parser enum, allowing custom parser implementations.

Public Members

parser_kind parser = {parser_kind::json}#

Which built‑in parser to use (default: json).

std::function<std::unique_ptr<parser_base>()> parser_factory#

Optional factory that creates a custom parser_base instance.

The factory must return a non‑null std::unique_ptr<parser_base>.

bool verify_tls = {true}#

Verify TLS certificates (default: true).

bool force_http_polling = {false}#

Force Engine.IO HTTP long‑polling instead of WebSocket.

Useful for environments where WebSocket upgrades are blocked.

std::vector<std::pair<std::string, std::string>> extra_headers#

Extra HTTP/WebSocket headers to send on the upgrade request.

std::optional<proxy_options> proxy#

Optional HTTP proxy and its Basic authentication credentials.

std::string engineio_path = {"/socket.io/"}#

Engine.IO endpoint path (default: /socket.io/).

This replaces any path supplied to client::connect(). A missing leading or trailing slash is added automatically; an empty path uses the default.

std::map<std::string, std::string> query#

Additional URL-encoded query parameters for the handshake.

Keys and values are percent-encoded. The reserved Engine.IO keys EIO, transport, and sid are rejected by client::connect() with std::invalid_argument.

int reconnect_attempts = {0}#

Number of retry attempts; zero disables reconnection.

std::chrono::milliseconds reconnect_delay = {2000}#

Initial back-off delay, doubled after each failed attempt.

std::chrono::milliseconds reconnect_delay_max = {30000}#

Maximum back-off delay between reconnection attempts.

double reconnect_randomization_factor = {0.5}#

Jitter factor applied to delays, in the range 0 to 1.

class client#

High‑level Socket.IO client.

Typical usage:

sioxx::client c;
c.set_open_listener([]{ std::cout << "connected\n"; });
c.connect("wss://example.com");
auto chat = c.socket("/chat");
chat->on("msg", [](const std::string&, sioxx::message data){
    std::cout << "msg: " << data.dump() << '\n';
});

Lifecycle listeners

void set_open_listener(std::function<void()> h)#

Set a callback that runs when the Engine.IO connection opens.

void set_close_listener(std::function<void(const std::string&)> h)#

Set a callback that runs when the Engine.IO connection closes.

void set_fail_listener(std::function<void()> h)#

Set a callback that runs when the Engine.IO handshake fails.

void set_reconnecting_listener(std::function<void()> h)#

Set a callback that runs when a reconnect attempt starts.

This callback runs after the configured back-off delay, immediately before opening the replacement Engine.IO connection.

void set_reconnect_listener(std::function<void(unsigned, unsigned)> h)#

Set a callback that runs when a reconnect attempt is scheduled.

The callback receives the zero-based attempt index and the selected back-off delay in milliseconds.

void set_error_listener(std::function<void(const std::string&)> h)#

Set a callback that runs on any error condition.

Public Functions

client()#

Construct a client with default configuration.

explicit client(const client_options &options)#

Construct a client by copying configuration.

Parameters:

options – Client options to copy.

explicit client(client_options &&options)#

Construct a client by moving configuration.

Parameters:

options – Client options to move from.

explicit client(boost::asio::io_context &io_context)#

Construct a client that uses a caller-owned I/O context.

The caller must keep the context alive for the lifetime of the client and is responsible for running it. sioxx never runs or stops this context.

Parameters:

io_context – Context used for all transport networking and callbacks.

client(boost::asio::io_context &io_context, const client_options &options)#

Construct a configured client using a caller-owned I/O context.

Parameters:
  • io_context – Context used for all transport networking and callbacks.

  • options – Client options to copy.

client(boost::asio::io_context &io_context, client_options &&options)#

Construct a configured client using a caller-owned I/O context.

Parameters:
  • io_context – Context used for all transport networking and callbacks.

  • options – Client options to move from.

~client()#

Destructor that requests shutdown and waits for background workers.

As with sync_close(), destroy the client outside library callbacks. A worker executing the destructor cannot wait for itself and finishes after the callback returns.

void connect(const std::string &uri)#

Open a connection to the given URI.

Parameters:

uri – Server URL (e.g. wss://host:port). Any path or query in the URL is replaced by client_options::engineio_path and client_options::query.

Throws:

std::invalid_argument – if the configured query contains a reserved Engine.IO parameter.

void close()#

Start closing the connection and return without waiting.

This operation is safe to call from library callbacks. Use sync_close() when the caller must wait for all background workers to stop. Repeated calls are safe.

void sync_close()#

Close the connection and wait for background workers to stop.

Do not call this operation from a library callback: a worker cannot wait for itself to finish. Use close() in callbacks instead. Repeated calls are safe.

bool opened() const#

Report whether the Engine.IO handshake has completed.

Returns:

true while the underlying Engine.IO connection is open.

std::string get_sessionid() const#

Return the current Engine.IO session identifier.

Returns:

The handshake sid, or an empty string before a session exists.

std::shared_ptr<sioxx::socket> socket(const std::string &nsp = "/", message auth = json())#

Obtain a socket for a specific namespace.

The returned socket can be used to register event listeners, emit events, and manually connect/disconnect the namespace. If the namespace socket already exists, a non-null auth replaces its current authentication payload; a null auth leaves it unchanged.

Parameters:
  • nsp – Namespace string (default is the root namespace /).

  • auth – Authentication payload sent in the namespace CONNECT packet.

Returns:

A shared pointer to a sioxx::socket bound to this client.

Socket#

A sioxx::socket represents a single Socket.IO namespace. It provides event listeners, event emission, acknowledgements and namespace connection lifecycle callbacks.

class socket : public std::enable_shared_from_this<socket>#

One namespace‑scoped communication channel.

The class mirrors the API of the original socket.io-client-cpp socket. Listeners are stored per‑event name; registering a listener for an existing name overwrites the previous one (consistent with the reference client).

All public methods are thread‑safe; internal state is protected by a mutex.

Event registration

void on(const std::string &event, event_listener listener)#

Register a listener for a specific event name.

If a listener for the same name already exists it is replaced.

Parameters:
  • event – Name of the event (e.g. "message").

  • listener – Callable that receives the event name and its payload.

void on(const std::string &event, ack_event_listener listener)#

Register a listener that can acknowledge an incoming event.

When the server includes an acknowledgement ID, acknowledge sends the supplied arguments back to the server and can be called at most once. If the event does not request an acknowledgement, acknowledge is empty.

Parameters:
  • event – Name of the event.

  • listener – Callable that receives the event, payload, and reply function.

void on_any(event_listener listener)#

Register a listener for every incoming event.

The listener is invoked after any listener registered for the event name. Registering another catch-all listener replaces the previous one.

Parameters:

listener – Callable that receives each event name and payload.

void on_any(ack_event_listener listener)#

Register an acknowledgement-aware listener for every event.

The listener is invoked after any listener registered for the event name. When the event requests an acknowledgement, the reply callback is shared with the named listener and sends at most one response between them. Registering another catch-all listener replaces the previous one.

Parameters:

listener – Callable that receives each event, payload, and reply function.

void off(const std::string &event)#

Remove the listener for a given event name.

void off_all()#

Remove all registered event listeners.

Connection lifecycle callbacks

void on_connect(connect_listener listener)#

Set a callback invoked when this namespace receives a CONNECT.

void on_disconnect(disconnect_listener listener)#

Set a callback invoked when this namespace receives a DISCONNECT.

Emission

void emit(const std::string &event, const message &data = json::array())#

Emit an event without expecting an acknowledgement.

Events emitted before the namespace connects are buffered and sent in order once its CONNECT packet is acknowledged by the server.

Parameters:
  • event – Event name.

  • data – Payload (default empty JSON array). May be any JSON value.

void emit(const std::string &event, const message &data, ack_callback callback)#

Emit an event and request an acknowledgement.

Events emitted before the namespace connects are buffered and sent in order once its CONNECT packet is acknowledged by the server.

Parameters:
  • event – Event name.

  • data – Payload.

  • callback – Function called when the server ACK arrives.

Namespace control

void connect()#

Send a CONNECT packet for this namespace.

void disconnect()#

Send a DISCONNECT packet for this namespace.

Internal callbacks – called by client_impl

void dispatch_event(const std::string &event, message data, int ack_id = -1)#

Deliver an incoming event from the server.

void dispatch_ack(int id, message data)#

Deliver an incoming ACK from the server.

void mark_connected(bool connected, const std::string &disconnect_reason = "")#

Mark the socket as (dis)connected.

Called by the client implementation after a successful CONNECT or when a DISCONNECT packet is received.

Parameters:
  • connected – New connection state.

  • disconnect_reason – Optional reason string (empty if none).

Public Types

using event_listener = std::function<void(const std::string &event, message data)>#

Type of a generic event listener (receives event name & payload).

using ack_callback = std::function<void(message data)>#

Callback used to receive or send acknowledgement data.

using ack_event_listener = std::function<void(const std::string &event, message data, ack_callback acknowledge)>#

Listener for events that may request an acknowledgement.

using connect_listener = std::function<void()>#

Listener for the connect event of this namespace.

using disconnect_listener = std::function<void(const std::string &reason)>#

Listener for the disconnect event of this namespace.

Public Functions

socket(std::weak_ptr<client_impl> client, std::string nsp, message auth = json())#

Construct a socket bound to a client and a namespace.

Parameters:
  • client – Weak reference to the owning client_impl.

  • nsp – Namespace string (e.g. "/chat").

  • auth – Authentication payload for namespace CONNECT packets.

inline const std::string &nsp() const#

Return the namespace this socket belongs to.

void set_auth(message auth)#

Replace the authentication payload used by the next CONNECT.

Passing a null message clears the payload.

message auth() const#

Return a copy of the current namespace authentication payload.

bool connected() const#

Whether the namespace is currently connected.

Messages#

Socket.IO values are represented directly with nlohmann::json. sioxx::json and sioxx::message are aliases for nlohmann::json, while sioxx::message_list represents an array of event arguments.

JSON‑based payload representation used throughout the library.

The original socket.io-client-cpp defined a hierarchy of sio::message types. sioxx simply aliases nlohmann::json – which already supports all required JSON primitives and binary blobs (json::binary_t).

namespace sioxx#

Typedefs

using json = nlohmann::json#

Alias for the JSON type used for every payload.

using message = json#

Alias for a single Socket.IO payload (formerly sio::message).

using message_list = json#

always a JSON array

Functions

inline message_list make_args()#

Create an empty argument list ([]).

Returns:

An empty message_list.

template<typename ...Args>
inline message_list make_args(Args&&... args)#

Create a message_list from a variadic pack of values.

Each argument is converted to json via the constructor, preserving types.

Template Parameters:

Args – Types of the arguments.

Parameters:

args – Arguments to be packed.

Returns:

A JSON array containing the supplied values.

inline message binary_message(const uint8_t *data, size_t len)#

Construct a binary payload from raw memory.

The returned JSON value holds a binary_t. The default JSON parser sends it as a Socket.IO binary attachment, while the MessagePack parser maps it onto MessagePack’s bin type.

Parameters:
  • data – Pointer to the first byte.

  • len – Number of bytes.

Returns:

A message containing the binary data.

inline message binary_message(std::vector<uint8_t> bytes)#

Construct a binary payload from a std::vector<uint8_t>.

Parameters:

bytes – Vector that will be moved into the JSON binary value.

Returns:

A message containing the binary data.

Parser extension API#

Applications can provide a custom wire-format parser by deriving from sioxx::parser_base and assigning a factory to sioxx::client_options::parser_factory.

enum class sioxx::packet_type : int#

Enumerates the different Socket.IO packet kinds.

Values match the official Socket.IO protocol specification.

Values:

enumerator connect#

Namespace connection request.

enumerator disconnect#

Namespace disconnection.

enumerator event#

Regular event with optional data.

enumerator ack#

Acknowledgement for a previous event.

enumerator connect_error#

Connection error payload.

enumerator binary_event#

Event that carries binary attachments.

enumerator binary_ack#

Ack that carries binary attachments.

struct packet#

Complete packet structure as used by parsers.

  • type – one of packet_type.

  • nsp – namespace (default “/”).

  • id – ACK identifier (‑1 if not used).

  • data – JSON payload (message).

  • attachments – number of binary attachments (relevant for binary packets).

Public Members

packet_type type = {packet_type::event}#

Packet type.

std::string nsp = {"/"}#

Namespace.

int id = {-1}#

ACK identifier.

json data#

Payload (JSON value)

int attachments = {0}#

Binary attachment count.

using sioxx::frame_writer = std::function<void(const std::string &payload, bool is_binary)>#

Signature of the callback that writes a fully‑encoded frame.

class parser_base#

Pure virtual base class that all parsers must derive from.

The parser receives a packet and a frame_writer. It must:

  • Encode a packet into one (or more) Engine.IO frames.

  • Decode a single Engine.IO payload back into a packet.

Note

The name() method is used for diagnostics and for selecting a parser in logs.

Public Functions

virtual ~parser_base() = default#

Virtual destructor.

virtual void encode(const packet &packet, const frame_writer &write) const = 0#

Encode a packet into an Engine.IO frame.

Parameters:
  • packet – Packet to encode.

  • write – Callback that forwards the encoded payload to the transport layer. The second argument indicates whether the frame is binary (true) or text (false).

virtual bool decode(const std::string &payload, bool is_binary, packet &out) = 0#

Decode a single Engine.IO payload.

Parameters:
  • payload – Raw payload received from the transport.

  • is_binarytrue if the payload is binary, false otherwise.

  • out – Destination packet – filled on successful decode.

Returns:

true if the packet was completely decoded; false if more data is required (e.g., waiting for binary attachments).

virtual std::string name() const = 0#

Human‑readable name of the parser implementation.

Returns:

A string such as "json_parser" or "msgpack_parser".