2. The Program

The complete program follows. It is generated from server-message.c in the companion examples repository.

/*
 * server-message.c -- vrtql_msg echo server.
 *
 * vrtql_msg_svr speaks libvws's higher-level message type (routing + headers +
 * content). Set the process hook; it echoes each inbound message back,
 * preserving its format. Pairs with client-message.
 */

#include <vws/server.h>
#include <vws/message.h>

#include "vwsx.h"

#include <stdio.h>

static const char* HOST = "127.0.0.1";
static const int   PORT = 8181;

/* Echo the inbound message back, preserving its format. Runs on a worker
 * thread. send() takes ownership of reply; we free the request. */
static void echo(vws_svr* s, vws_cid_t cid, vrtql_msg* m, void* ctx)
{
    (void)ctx;

    vrtql_msg* reply = vrtql_msg_new();
    reply->format    = m->format;
    vws_buffer_append(reply->content, m->content->data, m->content->size);

    ((vrtql_msg_svr*)s)->send(s, cid, reply, NULL);

    vrtql_msg_free(m);
}

int main(void)
{
    vrtql_msg_svr* server = vrtql_msg_svr_new(10, 0, 0);

    if (server == NULL)
    {
        vwsx_die("vrtql_msg_svr_new() failed");
    }

    server->process = echo;

    /*
     * Run/stop go through the base via the (vws_tcp_svr*) cast: the base
     * run/stop (vws_tcp_svr_run / vws_tcp_svr_stop) drive any server, as the
     * canonical test does.
     */
    vwsx_serve_stop_on_signal((vws_tcp_svr*)server);

    printf("server-message: vrtql_msg echo server on ws://%s:%d/websocket "
           "(Ctrl-C to stop)\n", HOST, PORT);

    vws_tcp_svr_run((vws_tcp_svr*)server, HOST, PORT);

    vrtql_msg_svr_free(server);

    return 0;
}