3. The Message API

Working atop the Client API is an optional Message API which provides additional features for the purpose of creating protocols similar to AMQP and MQTT. It consists of a specific message structure (vrtql_msg) and functions to send (vrtql_msg_send()) and receive (vrtql_msg_recv()) it. The message structure includes two maps (hashtables of string key/value pairs) and a payload. One map, called routing, is designed to hold routing information for messaging applications. The other map, called headers, is for application use. The payload can hold both text and binary data.

The Message API uses a normal WebSocket connection (vws_cnx) to send and receive messages in the same way as the Client API. The only difference is that it deals in vrtql_msg objects and automatically handles serialization and deserialization on and off the wire. Messages can be serialized in two formats: JSON and MessagePack. Both formats can be sent over the same connection on a message-by-message basis. That is, the Message API is able to auto-detect each incoming message’s format and deserialize accordingly. Thus connections support mixed-content messages: JSON and MessagePack.

The following is a basic example of using the API.

#include <vws/message.h>

int main()
{
    vws_cnx* cnx = vws_cnx_new();

    cstr uri = "ws://localhost:8181/websocket";
    if (vws_connect(cnx, uri) == false)
    {
        printf("Failed to connect to the WebSocket server\n");
        vws_cnx_free(cnx);
        return 1;
    }

    // Create a message
    vrtql_msg* request = vrtql_msg_new();

    vrtql_msg_set_routing(request, "key", "value");
    vrtql_msg_set_header(request, "key", "value");
    vrtql_msg_set_content(request, "payload");

    // Send
    if (vrtql_msg_send(cnx, request) < 0)
    {
        printf("Failed to send: %s\n", vws.e.text);
        vrtql_msg_free(request);
        vws_cnx_free(cnx);
        return 1;
    }

    // Receive
    vrtql_msg* reply = vrtql_msg_recv(cnx);

    if (reply == NULL)
    {
        // There was no message received and it resulted in timeout
    }
    else
    {
        // Free message
        vrtql_msg_free(reply);
    }

    // Cleanup
    vrtql_msg_free(request);

    vws_disconnect(cnx);
    vws_cnx_free(cnx);

    return 0;
}