Skip to content

WebSockets Client

The WebSockets client offers a high-level and a low-level API.

Starting a Session

To start a WebSockets client session using the high-level API, use the urlWebSockets API:

c
if (urlWebSocket("https://my.com/post", onEvent, arg, headers) < 0) {
    //  Error
}

This call return zero when closed, otherwise a negative status code. You can supply HTTP headers on the call if required.

Protocol Selection

To select the WebSocket sub-protocol, add a "Sec-WebSocket-Protocol" header.

c
if (urlWriteHeaders(up, "Sec-WebSocket-Protocol: real-time\r\n") < 0) {
    //  Connection error
}

Incoming Messages

When incoming messages are received, the onEvent callback will be invoked with the argument provided when urlWebSocket was called.

c
void onEvent(WebSocket *ws, int event, char *buf, ssize len, void *arg)
{
    switch (event) {
    case WS_EVENT_OPEN:
    case WS_EVENT_CLOSE:
    case WS_EVENT_ERROR:
        break;

    case WS_EVENT_MESSAGE:
    case WS_EVENT_PARTIAL_MESSAGE:
        printf("Received %s\n", buf);
        webSocketSend(ws, "%s", "Response message");
        break;
    }
}

Sending Data

Use webSocketSend to send a printf styled formatted message. To send a literal string, use webSocketSendString and to send binary data, use webSocketSendBlock.

c
webSocketSend(ws, "Hello %s", "World");
webSocketSendString(ws, "Hello World");
webSocketSendBlock(ws, WS, "Hello World", 11);

Closing Connections

To instruct the peer to do an orderly close, call webSocketSendClose.

c
webSocketSendClose(ws, WS_STATUS_OK, "End of session");

Low-Level API

WebSockets also provides a low-level API for more granular operation:

c
Url *url = urlAlloc(0);

if (urlStart(url, "GET", "wss://example.com/websockets/test") < 0) {
    // Connection failed
}
if (urlWriteHeaders(up, NULL) < 0 || urlFinalize(up) < 0) {
    //  Connection error
}
urlAsync(up, onEvent, up);

//  Serve events and wait for the connection to close
urlWait(up);
urlFree(url);

The urlAsync call defines the callback to invoke for incoming messages, errors and connection events. The urlWait call blocks until the connection is closed. This call is optional. You may wish to continue with other operations and call urlFree when processing is complete.

API