Vix.cpp v2.6.0 is here Read the blog
Skip to content

API Reference

This page summarizes the public API of the Vix WebSocket module.

Use it when you want a quick reference for headers, classes, callbacks, configuration, server APIs, client APIs, sessions, long-polling, metrics, persistence, OpenAPI, and attached HTTP + WebSocket runtime helpers.

Main header

Use the umbrella header for most applications:

cpp
#include <vix/websocket.hpp>
1

This includes the main WebSocket APIs.

Direct headers

cpp
#include <vix/websocket/config.hpp>
#include <vix/websocket/protocol.hpp>
#include <vix/websocket/client.hpp>
#include <vix/websocket/server.hpp>
#include <vix/websocket/session.hpp>
#include <vix/websocket/router.hpp>
#include <vix/websocket/MessageStore.hpp>
#include <vix/websocket/SqliteMessageStore.hpp>
#include <vix/websocket/Metrics.hpp>
#include <vix/websocket/App.hpp>
#include <vix/websocket/HttpApi.hpp>
#include <vix/websocket/LongPolling.hpp>
#include <vix/websocket/LongPollingBridge.hpp>
#include <vix/websocket/AttachedRuntime.hpp>
#include <vix/websocket/Runtime.hpp>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Namespace

The main namespace is:

cpp
namespace vix::websocket
1

Some combined runtime helpers live in:

cpp
namespace vix
1

Public API overview

APIPurpose
ConfigWebSocket runtime configuration.
JsonMessageTyped JSON message model.
ServerHigh-level WebSocket server.
LowLevelServerLow-level native async WebSocket engine.
SessionOne connected WebSocket client.
RouterDispatches open, close, error, and message events.
ClientNative WebSocket client.
LongPollingSessionIn-memory long-polling session buffer.
LongPollingManagerThread-safe manager for polling sessions.
LongPollingBridgeBridge between WebSocket and long-polling.
WebSocketMetricsPrometheus-style metrics counters and gauges.
IMessageStoreAbstract message persistence interface.
SqliteMessageStoreSQLite-backed message store.
AttachedRuntimeRuns WebSocket beside a vix::App.
register_ws_docs(...)Registers OpenAPI docs for WebSocket endpoints.

Config

Header:

cpp
#include <vix/websocket/config.hpp>
1

Type:

cpp
vix::websocket::Config
1

Fields:

cpp
std::size_t maxMessageSize = 64 * 1024;
std::chrono::seconds idleTimeout{60};
bool enablePerMessageDeflate = true;
bool autoPingPong = true;
std::chrono::seconds pingInterval{30};
1
2
3
4
5

Static functions:

cpp
static Config from_core(const vix::config::Config &core);
1

Example:

cpp
vix::config::Config core{".env"};

vix::websocket::Config ws =
    vix::websocket::Config::from_core(core);
1
2
3
4

Configuration keys

Common environment values:

dotenv
WEBSOCKET_HOST=0.0.0.0
WEBSOCKET_PORT=9090
WEBSOCKET_MAX_MESSAGE_SIZE=65536
WEBSOCKET_IDLE_TIMEOUT=60
WEBSOCKET_ENABLE_DEFLATE=true
WEBSOCKET_PING_INTERVAL=30
WEBSOCKET_AUTO_PING_PONG=true
1
2
3
4
5
6
7

Server

Header:

cpp
#include <vix/websocket/server.hpp>
1

Type:

cpp
vix::websocket::Server
1

Purpose:

txt
High-level WebSocket server with sessions, callbacks, rooms, broadcasting,
typed messages, shutdown, and optional long-polling bridge integration.
1
2

Server construction

cpp
Server(
    vix::config::Config &cfg,
    std::shared_ptr<vix::executor::RuntimeExecutor> executor);
1
2
3
cpp
Server(
    vix::config::Config &cfg,
    std::unique_ptr<vix::executor::RuntimeExecutor> executor);
1
2
3

Example:

cpp
vix::config::Config config{".env"};

auto executor =
    std::make_shared<vix::executor::RuntimeExecutor>(4);

vix::websocket::Server ws{config, executor};
1
2
3
4
5
6

Server callback types

cpp
using OpenHandler =
    std::function<void(Session &)>;

using CloseHandler =
    std::function<void(Session &)>;

using ErrorHandler =
    std::function<void(Session &, const std::string &)>;

using MessageHandler =
    std::function<void(Session &, const std::string &)>;

using TypedMessageHandler =
    std::function<void(Session &, const std::string &, const vix::json::kvs &)>;
1
2
3
4
5
6
7
8
9
10
11
12
13
14

Server callbacks

cpp
void on_open(OpenHandler fn);
void on_close(CloseHandler fn);
void on_error(ErrorHandler fn);
void on_message(MessageHandler fn);
void on_typed_message(TypedMessageHandler fn);
1
2
3
4
5

Example:

cpp
ws.on_message(
  [](vix::websocket::Session &session, const std::string &message)
  {
    session.send_text("echo: " + message);
  });
1
2
3
4
5

Typed example:

cpp
ws.on_typed_message(
  [](vix::websocket::Session &session,
     const std::string &type,
     const vix::json::kvs &payload)
  {
    (void)payload;

    if (type == "ping")
    {
      session.send_text("pong");
    }
  });
1
2
3
4
5
6
7
8
9
10
11
12

Server lifecycle

cpp
void start();
void stop_async();
void stop();
void listen_blocking();
1
2
3
4

Use:

cpp
ws.start();
1

For shutdown:

cpp
ws.stop_async();
ws.stop();
1
2

stop_async() requests non-blocking shutdown.

stop() performs final blocking shutdown and joins internal server threads.

Server rooms

cpp
void join_room(std::shared_ptr<Session> session, const RoomId &room);
void leave_room(std::shared_ptr<Session> session, const RoomId &room);
1
2

Example:

cpp
ws.on_open([&ws](vix::websocket::Session &session)
{
  ws.join_room(session.shared_from_this(), "chat:general");
});
1
2
3
4

Server broadcasting

cpp
void broadcast_text(const std::string &text);
void broadcast_text_to_room(const RoomId &room, const std::string &text);
1
2

Examples:

cpp
ws.broadcast_text("global message");
ws.broadcast_text_to_room("chat:general", "room message");
1
2

Server long-polling bridge

cpp
void attach_long_polling_bridge(LongPollingBridge *bridge);
1

Example:

cpp
vix::websocket::LongPollingBridge bridge{
    &metrics,
    std::chrono::seconds{60},
    256};

ws.attach_long_polling_bridge(&bridge);
1
2
3
4
5
6

Server information

Common server information APIs include:

cpp
int port() const;
int bound_port() const;
1
2

Use these to inspect the configured or bound WebSocket port when supported by the current build.

LowLevelServer

Header:

cpp
#include <vix/websocket/websocket.hpp>
1

Type:

cpp
vix::websocket::LowLevelServer
1

Purpose:

txt
Low-level asynchronous WebSocket server engine.
1

It owns:

  • async I/O context
  • TCP listener
  • accept loop
  • I/O worker threads
  • session creation
  • server shutdown state

Most applications should use vix::websocket::Server instead.

LowLevelServer API

cpp
LowLevelServer(
    vix::config::Config &coreConfig,
    std::shared_ptr<vix::executor::RuntimeExecutor> executor,
    std::shared_ptr<Router> router);

~LowLevelServer();

void run();
void stop_async();
void join_threads();

bool is_stop_requested() const;
1
2
3
4
5
6
7
8
9
10
11
12

Session

Header:

cpp
#include <vix/websocket/session.hpp>
1

Type:

cpp
vix::websocket::Session
1

Purpose:

txt
Represents one connected WebSocket client.
1

A session manages:

  • HTTP Upgrade handshake
  • frame reads
  • frame writes
  • text messages
  • binary messages
  • close handling
  • heartbeat
  • idle timeout
  • router dispatch

Session construction

cpp
Session(
    std::unique_ptr<tcp_stream> stream,
    const Config &cfg,
    std::shared_ptr<Router> router,
    std::shared_ptr<vix::executor::RuntimeExecutor> executor,
    std::shared_ptr<io_context> ioc);
1
2
3
4
5
6

Most applications do not construct sessions directly.

The low-level server creates them internally.

Session API

cpp
task<void> run();

void send_text(std::string_view text);
void send_binary(const void *data, std::size_t size);

void close(std::string reason = {});
bool is_open() const noexcept;

void emit_error(const std::string &message);
void shutdown_now() noexcept;
1
2
3
4
5
6
7
8
9
10

Example:

cpp
ws.on_message(
  [](vix::websocket::Session &session, const std::string &message)
  {
    if (session.is_open())
    {
      session.send_text("received: " + message);
    }
  });
1
2
3
4
5
6
7
8

Router

Header:

cpp
#include <vix/websocket/router.hpp>
1

Type:

cpp
vix::websocket::Router
1

Purpose:

txt
Lightweight event dispatcher for WebSocket sessions.
1

Router handler types

cpp
using OpenHandler =
    std::function<void(Session &)>;

using CloseHandler =
    std::function<void(Session &)>;

using ErrorHandler =
    std::function<void(Session &, const std::string &)>;

using MessageHandler =
    std::function<void(Session &, std::string)>;
1
2
3
4
5
6
7
8
9
10
11

Router registration API

cpp
void on_open(OpenHandler cb);
void on_close(CloseHandler cb);
void on_error(ErrorHandler cb);
void on_message(MessageHandler cb);
1
2
3
4

Router dispatch API

cpp
void handle_open(Session &session) const;
void handle_close(Session &session) const;
void handle_error(Session &session, const std::string &error) const;
void handle_message(Session &session, std::string payload) const;
1
2
3
4

Router inspection API

cpp
bool has_open_handler() const noexcept;
bool has_close_handler() const noexcept;
bool has_error_handler() const noexcept;
bool has_message_handler() const noexcept;
1
2
3
4

Most applications should register callbacks through Server instead of using Router directly.

Client

Header:

cpp
#include <vix/websocket/client.hpp>
1

Type:

cpp
vix::websocket::Client
1

Purpose:

txt
Native WebSocket client with async connect, text messages, typed JSON messages,
heartbeat, and optional reconnect.
1
2

The client exposes callback setters, connection control, text sending, typed JSON sending, ping, close, and connection state helpers. :contentReference[oaicite:0]

Client construction

cpp
static std::shared_ptr<Client> create(
    std::string host,
    std::string port,
    std::string target = "/");
1
2
3
4

Example:

cpp
auto client =
    vix::websocket::Client::create("127.0.0.1", "9090", "/");
1
2

Client callback types

cpp
using OpenHandler =
    std::function<void()>;

using MessageHandler =
    std::function<void(const std::string &)>;

using CloseHandler =
    std::function<void()>;

using ErrorHandler =
    std::function<void(const std::string &)>;
1
2
3
4
5
6
7
8
9
10
11

Client callbacks

cpp
void on_open(OpenHandler cb);
void on_message(MessageHandler cb);
void on_close(CloseHandler cb);
void on_error(ErrorHandler cb);
1
2
3
4

Example:

cpp
client->on_open([client]()
{
  client->send_text("hello");
});

client->on_message([](const std::string &message)
{
  vix::print("received:", message);
});
1
2
3
4
5
6
7
8
9

Client connection API

cpp
void connect();
void close();

bool is_connected() const noexcept;
1
2
3
4

connect() starts the client runtime thread and async connection flow.

close() closes the connection, stops runtime activity, and joins client threads when safe.

Client sending API

cpp
void send_text(const std::string &text);

void send_json_message(
    const std::string &type,
    const vix::json::kvs &payload);

void send_json_message(
    const std::string &type,
    std::initializer_list<vix::json::token> payloadTokens);

void send(
    const std::string &type,
    const vix::json::kvs &payload);

void send(
    const std::string &type,
    std::initializer_list<vix::json::token> payloadTokens);

void send_ping();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

Example:

cpp
client->send_json_message(
    "chat.message",
    {
      {"text", "Hello"}
    });
1
2
3
4
5

The send(...) overloads are convenience aliases for typed JSON sending.

Client heartbeat and reconnect

cpp
void enable_heartbeat(std::chrono::seconds interval);

void enable_auto_reconnect(
    bool enable,
    std::chrono::seconds delay = std::chrono::seconds{3});
1
2
3
4
5

Example:

cpp
client->enable_heartbeat(std::chrono::seconds{30});
client->enable_auto_reconnect(true, std::chrono::seconds{3});
1
2

JsonMessage

Header:

cpp
#include <vix/websocket/protocol.hpp>
1

Type:

cpp
vix::websocket::JsonMessage
1

Purpose:

txt
Structured typed WebSocket message model.
1

Common fields:

cpp
std::string id;
std::string kind;
std::string room;
std::string type;
std::string ts;
vix::json::kvs payload;
1
2
3
4
5
6

Common shape:

json
{
  "id": "00000000000000000001",
  "kind": "event",
  "room": "general",
  "type": "chat.message",
  "ts": "2026-05-17T10:00:00Z",
  "payload": {
    "text": "Hello"
  }
}
1
2
3
4
5
6
7
8
9
10

JsonMessage API

Common API:

cpp
static std::optional<JsonMessage> parse(const std::string &text);

std::string to_json_string() const;
1
2
3

Example:

cpp
auto parsed = vix::websocket::JsonMessage::parse(text);

if (parsed)
{
  vix::print("type:", parsed->type);
}
1
2
3
4
5
6

Protocol detail API

Header:

cpp
#include <vix/websocket/protocol.hpp>
1

The protocol layer includes internal frame helpers under:

cpp
namespace vix::websocket::detail
1

Important internal types include:

cpp
enum class Opcode;
struct Frame;
struct FrameHeader;
1
2
3

Frame helpers are used by the client and session implementation.

Most applications should use Server, Session, Client, and JsonMessage instead of protocol internals.

LongPollingSession

Header:

cpp
#include <vix/websocket/LongPolling.hpp>
1

Type:

cpp
vix::websocket::LongPollingSession
1

Fields:

cpp
std::string id;
std::chrono::steady_clock::time_point lastSeen;
std::deque<JsonMessage> buffer;
1
2
3

API:

cpp
LongPollingSession();
explicit LongPollingSession(std::string sessionId);

void touch() noexcept;

bool is_expired(
    std::chrono::seconds ttl,
    std::chrono::steady_clock::time_point now) const noexcept;

void enqueue(const JsonMessage &msg, std::size_t maxBufferSize);

std::vector<JsonMessage> drain(std::size_t maxCount);
1
2
3
4
5
6
7
8
9
10
11
12

The session stores a bounded FIFO buffer and refreshes lastSeen when messages are enqueued or drained. :contentReference[oaicite:1]

LongPollingManager

Header:

cpp
#include <vix/websocket/LongPolling.hpp>
1

Type:

cpp
vix::websocket::LongPollingManager
1

Purpose:

txt
Thread-safe manager for long-polling sessions and buffers.
1

LongPollingManager construction

cpp
LongPollingManager(
    std::chrono::seconds sessionTtl = std::chrono::seconds{60},
    std::size_t maxBufferPerSession = 256,
    WebSocketMetrics *metrics = nullptr);
1
2
3
4

Example:

cpp
vix::websocket::LongPollingManager manager{
    std::chrono::seconds{60},
    256,
    &metrics};
1
2
3
4

LongPollingManager API

cpp
void push_to(const SessionId &sessionId, const JsonMessage &message);

std::vector<JsonMessage> poll(
    const SessionId &sessionId,
    std::size_t maxMessages = 50,
    bool createIfMissing = true);

void sweep_expired();

std::size_t session_count() const;

std::size_t buffer_size(const SessionId &sessionId) const;
1
2
3
4
5
6
7
8
9
10
11
12

push_to(...) creates the session if missing, poll(...) drains up to maxMessages, and sweep_expired() removes inactive sessions based on TTL. :contentReference[oaicite:2]

LongPollingBridge

Header:

cpp
#include <vix/websocket/LongPollingBridge.hpp>
1

Type:

cpp
vix::websocket::LongPollingBridge
1

Purpose:

txt
Bridge between WebSocket JsonMessage events and HTTP long-polling sessions.
1

LongPollingBridge aliases

cpp
using SessionId = std::string;

using Resolver =
    std::function<SessionId(const JsonMessage &)>;

using HttpToWsForward =
    std::function<void(const JsonMessage &)>;
1
2
3
4
5
6
7

LongPollingBridge constructors

With external manager:

cpp
LongPollingBridge(
    LongPollingManager &manager,
    Resolver resolver = {},
    HttpToWsForward httpToWs = {});
1
2
3
4

Owning manager:

cpp
LongPollingBridge(
    WebSocketMetrics *metrics,
    std::chrono::seconds sessionTtl = std::chrono::seconds{60},
    std::size_t maxBufferPerSession = 256,
    Resolver resolver = {},
    HttpToWsForward httpToWs = {});
1
2
3
4
5
6

LongPollingBridge API

cpp
void on_ws_message(const JsonMessage &msg);

std::vector<JsonMessage> poll(
    const SessionId &sessionId,
    std::size_t maxMessages = 50,
    bool createIfMissing = true);

void send_from_http(
    const SessionId &sessionId,
    const JsonMessage &msg);

LongPollingManager &manager() noexcept;
const LongPollingManager &manager() const noexcept;

std::size_t session_count() const;
std::size_t buffer_size(const SessionId &sid) const;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

Default resolution:

txt
if msg.room is not empty:
  session id = "room:" + msg.room
else:
  session id = "broadcast"
1
2
3
4

WebSocketMetrics

Header:

cpp
#include <vix/websocket/Metrics.hpp>
1

Type:

cpp
vix::websocket::WebSocketMetrics
1

Purpose:

txt
Prometheus-style metrics for WebSocket and long-polling.
1

WebSocketMetrics fields

cpp
std::atomic<std::uint64_t> connections_total{0};
std::atomic<std::uint64_t> connections_active{0};

std::atomic<std::uint64_t> messages_in_total{0};
std::atomic<std::uint64_t> messages_out_total{0};

std::atomic<std::uint64_t> errors_total{0};

std::atomic<std::uint64_t> lp_sessions_total{0};
std::atomic<std::uint64_t> lp_sessions_active{0};

std::atomic<std::uint64_t> lp_polls_total{0};

std::atomic<std::uint64_t> lp_messages_buffered{0};
std::atomic<std::uint64_t> lp_messages_enqueued_total{0};
std::atomic<std::uint64_t> lp_messages_drained_total{0};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

WebSocketMetrics API

cpp
std::string render_prometheus() const;
1

Example:

cpp
vix::websocket::WebSocketMetrics metrics;

metrics.connections_total.fetch_add(1, std::memory_order_relaxed);

std::string text = metrics.render_prometheus();
1
2
3
4
5

Metrics exporter

cpp
void run_metrics_http_exporter(
    WebSocketMetrics &metrics,
    const std::string &address = "0.0.0.0",
    std::uint16_t port = 9100);
1
2
3
4

Example:

cpp
vix::websocket::run_metrics_http_exporter(
    metrics,
    "0.0.0.0",
    9100);
1
2
3
4

The exporter serves Prometheus text at:

txt
GET /metrics
1

The exporter reads an HTTP request head, returns metrics.render_prometheus() for /metrics, and returns 404 for other targets. :contentReference[oaicite:3]

IMessageStore

Header:

cpp
#include <vix/websocket/MessageStore.hpp>
1

Type:

cpp
vix::websocket::IMessageStore
1

Purpose:

txt
Abstract persistence interface for JsonMessage history and replay.
1

IMessageStore API

cpp
virtual ~IMessageStore() = default;

virtual void append(const JsonMessage &msg) = 0;

virtual std::vector<JsonMessage> list_by_room(
    const std::string &room,
    std::size_t limit,
    const std::optional<std::string> &before_id = std::nullopt) = 0;

virtual std::vector<JsonMessage> replay_from(
    const std::string &start_id,
    std::size_t limit) = 0;
1
2
3
4
5
6
7
8
9
10
11
12

SqliteMessageStore

Header:

cpp
#include <vix/websocket/SqliteMessageStore.hpp>
1

Type:

cpp
vix::websocket::SqliteMessageStore
1

Purpose:

txt
SQLite-backed implementation of IMessageStore.
1

SqliteMessageStore construction

cpp
explicit SqliteMessageStore(const std::string &db_path);
1

Example:

cpp
vix::websocket::SqliteMessageStore store{"messages.db"};
1

SqliteMessageStore API

cpp
~SqliteMessageStore() override;

void append(const JsonMessage &msg) override;

std::vector<JsonMessage> list_by_room(
    const std::string &room,
    std::size_t limit,
    const std::optional<std::string> &before_id = std::nullopt) override;

std::vector<JsonMessage> replay_from(
    const std::string &start_id,
    std::size_t limit) override;
1
2
3
4
5
6
7
8
9
10
11
12

The SQLite store opens or creates the database, enables WAL mode, creates the messages table, and stores fields such as id, kind, room, type, ts, and payload_json.

App

Header:

cpp
#include <vix/websocket/App.hpp>
1

Type:

cpp
vix::websocket::App
1

Purpose:

txt
High-level WebSocket application wrapper.
1

It manages:

  • config
  • executor
  • underlying WebSocket server
  • typed message routes
  • shutdown

App handler type

cpp
using TypedHandler =
    std::function<void(
        Session &,
        const std::string &type,
        const vix::json::kvs &payload)>;
1
2
3
4
5

App construction

cpp
App(
    const std::string &configPath,
    std::shared_ptr<vix::executor::RuntimeExecutor> executor);
1
2
3

Example:

cpp
auto executor =
    std::make_shared<vix::executor::RuntimeExecutor>(4);

vix::websocket::App app{".env", executor};
1
2
3
4

App API

cpp
App &ws(const std::string &endpoint, TypedHandler handler);

void run_blocking();
void stop() noexcept;

Server &server() noexcept;
vix::config::Config &config() noexcept;

std::shared_ptr<vix::executor::RuntimeExecutor> executor() noexcept;
1
2
3
4
5
6
7
8
9

AttachedRuntime

Header:

cpp
#include <vix/websocket/AttachedRuntime.hpp>
1

Type:

cpp
vix::websocket::AttachedRuntime
1

Purpose:

txt
Attach a WebSocket server to a vix::App with shared lifecycle.
1

AttachedRuntime construction

cpp
AttachedRuntime(
    vix::App &app,
    vix::websocket::Server &ws,
    std::shared_ptr<vix::executor::RuntimeExecutor> exec);
1
2
3
4

Example:

cpp
vix::App app;

auto executor =
    std::make_shared<vix::executor::RuntimeExecutor>(4);

vix::websocket::Server ws{app.config(), executor};

vix::websocket::AttachedRuntime runtime{app, ws, executor};
1
2
3
4
5
6
7
8

The constructor starts the WebSocket server and registers an HTTP shutdown callback. :contentReference[oaicite:4]

AttachedRuntime API

cpp
void request_stop() noexcept;
void finalize_shutdown() noexcept;
1
2

request_stop() requests non-blocking WebSocket shutdown.

finalize_shutdown() performs final blocking cleanup by stopping the WebSocket server and then stopping the shared executor. :contentReference[oaicite:5]

Combined runtime helpers

Header:

cpp
#include <vix/websocket/AttachedRuntime.hpp>
1

Namespace:

cpp
namespace vix
1

register_ws_openapi_docs_once

cpp
void register_ws_openapi_docs_once();
1

Registers WebSocket OpenAPI docs once per process.

Default documented routes:

txt
GET  /ws
GET  /ws/poll
POST /ws/send
GET  /metrics
1
2
3
4

run_http_and_ws

cpp
void run_http_and_ws(
    vix::App &app,
    vix::websocket::Server &ws,
    std::shared_ptr<vix::executor::RuntimeExecutor> exec,
    const vix::config::Config &cfg);
1
2
3
4
5

Port overload:

cpp
void run_http_and_ws(
    vix::App &app,
    vix::websocket::Server &ws,
    std::shared_ptr<vix::executor::RuntimeExecutor> exec,
    int port);
1
2
3
4
5

Purpose:

txt
Run HTTP and WebSocket together with shared config and executor.
1

The combined runner registers WebSocket docs, HTTP OpenAPI routes, Swagger UI routes, creates an AttachedRuntime, then runs the HTTP app. :contentReference[oaicite:6]

serve_http_and_ws

cpp
serve_http_and_ws(configPath, port, fn);
serve_http_and_ws(fn);
1
2

Purpose:

txt
High-level helper that creates Config, RuntimeExecutor, App, and WebSocket Server,
then lets the caller configure HTTP and WebSocket behavior.
1
2

Example:

cpp
vix::serve_http_and_ws([](vix::App &app, vix::websocket::Server &ws)
{
  app.get("/", [](vix::Request &req, vix::Response &res)
  {
    (void)req;

    res.text("HTTP + WebSocket");
  });

  ws.on_message(
    [](vix::websocket::Session &session, const std::string &message)
    {
      session.send_text("echo: " + message);
    });
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

OpenAPI docs

Header:

cpp
#include <vix/websocket/openapi_docs.hpp>
1

Namespace:

cpp
namespace vix::websocket::openapi
1

Function:

cpp
void register_ws_docs(
    std::string ws_upgrade_path = "/ws",
    std::string lp_poll_path = "/ws/poll",
    std::string lp_send_path = "/ws/send",
    std::string metrics_path = "/metrics");
1
2
3
4
5

Example:

cpp
vix::websocket::openapi::register_ws_docs();
1

Custom paths:

cpp
vix::websocket::openapi::register_ws_docs(
    "/api/ws",
    "/api/ws/poll",
    "/api/ws/send",
    "/api/ws/metrics");
1
2
3
4
5

HTTP API helpers

Header:

cpp
#include <vix/websocket/HttpApi.hpp>
1

Namespace:

cpp
namespace vix::websocket::http
1

Purpose:

txt
Helpers for long-polling HTTP endpoints and request parsing.
1

Common endpoints:

txt
GET  /ws/poll
POST /ws/send
1
2

The helper code supports URL decoding, query parameter extraction, request target extraction, and integration with LongPollingBridge.

Minimal server example

cpp
#include <memory>
#include <string>

#include <vix/config/Config.hpp>
#include <vix/executor/RuntimeExecutor.hpp>
#include <vix/websocket.hpp>

int main()
{
  vix::config::Config config{".env"};

  auto executor =
      std::make_shared<vix::executor::RuntimeExecutor>(4);

  vix::websocket::Server ws{config, executor};

  ws.on_message(
    [](vix::websocket::Session &session, const std::string &message)
    {
      session.send_text("echo: " + message);
    });

  ws.start();

  return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

Minimal client example

cpp
#include <memory>
#include <string>

#include <vix/print.hpp>
#include <vix/websocket.hpp>

int main()
{
  auto client =
      vix::websocket::Client::create("127.0.0.1", "9090", "/");

  client->on_open([client]()
  {
    client->send_text("hello");
  });

  client->on_message([](const std::string &message)
  {
    vix::print("received:", message);
  });

  client->connect();

  return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

Minimal attached runtime example

cpp
#include <memory>
#include <string>

#include <vix.hpp>
#include <vix/websocket.hpp>

int main()
{
  vix::App app;

  auto executor =
      std::make_shared<vix::executor::RuntimeExecutor>(4);

  vix::websocket::Server ws{app.config(), executor};

  ws.on_message(
    [](vix::websocket::Session &session, const std::string &message)
    {
      session.send_text("echo: " + message);
    });

  vix::websocket::AttachedRuntime runtime{app, ws, executor};

  app.run(8080);

  return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

API by use case

Use caseAPI
Start WebSocket servervix::websocket::Server
Handle connection openServer::on_open(...)
Handle raw messageServer::on_message(...)
Handle typed JSON messageServer::on_typed_message(...)
Reply to one clientSession::send_text(...)
Send binary payloadSession::send_binary(...)
Close one clientSession::close(...)
Broadcast to all clientsServer::broadcast_text(...)
Broadcast to roomServer::broadcast_text_to_room(...)
Join roomServer::join_room(...)
Leave roomServer::leave_room(...)
Create C++ clientClient::create(...)
Send client textClient::send_text(...)
Send client typed JSONClient::send_json_message(...)
Enable heartbeatClient::enable_heartbeat(...)
Enable reconnectClient::enable_auto_reconnect(...)
Use long-pollingLongPollingManager, LongPollingBridge
Export metricsWebSocketMetrics::render_prometheus()
Run metrics exporterrun_metrics_http_exporter(...)
Store messagesIMessageStore
Store in SQLiteSqliteMessageStore
Attach HTTP + WebSocketAttachedRuntime
Register OpenAPI docsregister_ws_docs(...)

Released under the MIT License.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.