3. Walk-through

The program needs the WebSocket API header and the examples' support header:

#include <vws/websocket.h>

#include "vwsx.h"

The connection is opened in a single call:

vws_cnx* cnx = vwsx_connect(URI);

vwsx_connect performs vws_cnx_new() and then vws_connect() against the URI (ws://localhost:8181/websocket), exiting through vwsx_die if either step fails; a wss URI would negotiate TLS transparently. On return cnx is a connected vws_cnx.

The first exchange sends a single text frame:

if (vws_frame_send_text(cnx, "hello over a text frame") < 0)
{
    vwsx_die("vws_frame_send_text() failed");
}

vws_frame_send_text() returns the number of bytes written, or a value less than zero on error. The reply is collected and printed by the program's recv_and_print helper:

vws_msg* reply = vws_msg_recv(cnx);

if (reply == NULL)
{
    vwsx_die("vws_msg_recv() returned NULL waiting for %s", what);
}

printf("client-basic: %s reply -- %zu bytes (opcode %u): %.*s\n",
       what,
       reply->data->size,
       reply->opcode,
       (int)reply->data->size,
       (const char*)reply->data->data);

vws_msg_free(reply);

vws_msg_recv() blocks until a complete message arrives and returns it, or returns NULL on timeout. The payload bytes are reply->data->data and their length is reply->data->size; the frame type is in reply->opcode. Each received message is released with vws_msg_free().

The second exchange sends a four-byte binary message rather than a text frame:

const unsigned char payload[] = { 0x01, 0x02, 0x03, 0x04 };
if (vws_msg_send_binary(cnx, (ucstr)payload, sizeof(payload)) < 0)
{
    vwsx_die("vws_msg_send_binary() failed");
}

Unlike the frame call, vws_msg_send_binary() takes an explicit length, so the payload may contain embedded NUL bytes. Its reply is received and printed by the same helper.

Finally the program shuts the connection down in two steps:

vws_disconnect(cnx);
vws_cnx_free(cnx);

vws_disconnect() performs an orderly WebSocket close and vws_cnx_free() releases the connection object; after this the connection must not be used again.