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", onRead, 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 onRead callback will be invoked with the argument provided when urlWebSocket was called.

c
void onRead(WebSocket *ws, char *buf, ssize len, void *arg)
{
    printf("Received %s\n", buf);
    webSocketSend(ws, "%s", "Response message");
}

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 granulaa

c
Url *url = urlAlloc(0);

if (urlStart(url, "GET", "wss://example.com/websockets/test") < 0) {
    // Connection failed
}
if (urlWriteHeaders(up, NULL) < 0) {
    //  Connection error
}
if (urlRunSocket(url, onEvent, NULL) <= 0) {
    // Closed or error
}
urlFree(url);

API