Skip to content

WebSockets API

The WebSockets library is a client and server implementation of the WebSockets over HTTP protocol.

Normal HTTP connections follow a request/response paradigm and do not easily support asynchronous communications or unsolicited data pushed from the server to the client. WebSockets solves this by supporting bidirectional, full-duplex communications over persistent connections. A WebSocket connection is established over a standard HTTP connection and is then upgraded without impacting the original connection. This means it will work with existing networking infrastructure including firewalls and proxies.

WebSockets is currently supported in the current releases of all major browsers, including: Chrome, Firefox, IE, Opera and Safari.

WebSockets include:

  • WebSockets RFC 6455 engine
  • Support over HTTP and HTTPS/TLS
  • Multiple WebSockets connections
  • Configurable UTF-8 validation
  • Binding to C functions for incoming data receipt
  • Paralelism via fiber coroutines

Function Index

WebSocket *webSocketAlloc(RSocket *sock, bool client)
 Allocate a new WebSocket object.
voidwebSocketAsync(WebSocket *ws, WebSocketProc callback, void *arg, RBuf *buf)
 Configure WebSocket for asynchronous operation with callback.
voidwebSocketFree(WebSocket *ws)
 Free a WebSocket object.
cchar *webSocketGetClientKey(WebSocket *ws)
 Get the client key.
cchar *webSocketGetCloseReason(WebSocket *ws)
 Get the close reason supplied by the peer.
void *webSocketGetData(WebSocket *ws)
 Get the WebSocket private data.
cchar *webSocketGetErrorMessage(WebSocket *ws)
 Get the error message for the current message.
ssizewebSocketGetMessageLength(WebSocket *ws)
 Get the message length for the current message.
boolwebSocketGetOrderlyClosed(WebSocket *ws)
 Test if WebSocket connection was orderly closed by sending an acknowledged close message.
char *webSocketGetProtocol(WebSocket *ws)
 Get the selected WebSocket protocol selected by the server.
ssizewebSocketGetState(WebSocket *ws)
 Get the WebSocket state.
intwebSocketProcess(WebSocket *ws)
 Process a packet of data containing webSocket frames and data.
voidwebSocketSelectProtocol(WebSocket *ws, cchar *protocol)
 Select the WebSocket protocol.
ssizewebSocketSend(WebSocket *ws, cchar *fmt, ...) PRINTF_ATTRIBUTE(2
 Send a UTF-8 text message to the WebSocket peer.
ssizewebSocketSendBlock(WebSocket *ws, int type, cchar *msg, ssize len)
 Send a message of a given type to the WebSocket peer.
ssizewebSocketSendClose(WebSocket *ws, int status, cchar *reason)
 Send a close message to the WebSocket peer.
ssizewebSocketSendJson(WebSocket *ws, Json *json, int nid, cchar *key)
 Send a json object to the WebSocket peer.
ssize ssizewebSocketSendString(WebSocket *ws, cchar *buf)
 Send a string to the WebSocket peer.
voidwebSocketSetClientKey(WebSocket *ws, cchar *clientKey)
 Set the client key.
voidwebSocketSetData(WebSocket *ws, void *data)
 Set the WebSocket private data.
voidwebSocketSetFiber(WebSocket *ws, RFiber *fiber)
 Set the WebSocket fiber.
voidwebSocketSetLimits(WebSocket *ws, ssize maxFrame, ssize maxMessage)
 Set the maximum frame size and message size.
voidwebSocketSetPingPeriod(WebSocket *ws, Time pingPeriod)
 Set the ping period.
voidwebSocketSetValidateUTF(WebSocket *ws, bool validateUTF)
 Set whether to validate UTF8 codepoints.
intwebSocketWait(WebSocket *ws, Time deadline)
 Wait for the WebSocket connection to close.

Typedef Index

WebSocketWebSocket WebSockets RFC 6455 implementation for client and server communications.
WebSocketProcWebSocket callback procedure invoked when a message is received or the connection is first opened.

Defines

#defineWEB_MORE   0x1000
 Flag for webSocketSendBlock to indicate there are more frames for this message.
#defineWS_CLIENT   1
 Instance executing as a client.
#defineWS_EVENT_CLOSE   4
 WebSocket connection is closed.
#defineWS_EVENT_ERROR   3
 WebSocket error is detected.
#defineWS_EVENT_MESSAGE   1
 WebSocket full (or last part of) message is received.
#defineWS_EVENT_OPEN   0
 WebSocket connection is open.
#defineWS_EVENT_PARTIAL_MESSAGE   2
 WebSocket partial message is received.
#defineWS_MAX_CONTROL   125
 Maximum bytes in control message.
#defineWS_MAX_FRAME   131072
 Maximum frame size.
#defineWS_MAX_MESSAGE   (1024 * 1024)
 Maximum message size, zero for no limit.
#defineWS_MSG_BINARY   0x2
 webSendBlock type for binary messages.
#defineWS_MSG_CLOSE   0x8
 webSendBlock type for close message.
#defineWS_MSG_CONT   0x0
 Continuation of WebSocket message.
#defineWS_MSG_CONTROL   0x8
 Start of control messages.
#defineWS_MSG_MAX   0xB
 Max message type for webSendBlock.
#defineWS_MSG_MORE   0x10
 Use on first call to webSendBlock to indicate more data to follow.
#defineWS_MSG_PING   0x9
 webSendBlock type for ping messages.
#defineWS_MSG_PONG   0xA
 webSendBlock type for pong messages.
#defineWS_MSG_TEXT   0x1
 webSendBlock type for text messages.
#defineWS_SERVER   0
 Instance executing as a server.
#defineWS_STATE_CLOSED   3
 WebSocket is closed.
#defineWS_STATE_CLOSING   2
 WebSocket is closing.
#defineWS_STATE_CONNECTING   0
 WebSocket connection is being established.
#defineWS_STATE_OPEN   1
 WebSocket handsake is complete and ready for communications.
#defineWS_STATUS_COMMS_ERROR   1006
 TCP/IP communications error
#defineWS_STATUS_FRAME_TOO_LARGE   1004
 Reserved.
#defineWS_STATUS_GOING_AWAY   1001
 Endpoint is going away.
#defineWS_STATUS_INTERNAL_ERROR   1011
 Server terminating due to an internal error.
#defineWS_STATUS_INVALID_UTF8   1007
 Text message has invalid UTF-8.
#defineWS_STATUS_MAX   5000
 Maximum error status (less one).
#defineWS_STATUS_MESSAGE_TOO_LARGE   1009
 Message is too large.
#defineWS_STATUS_MISSING_EXTENSION   1010
 Unsupported WebSockets extension.
#defineWS_STATUS_NO_STATUS   1005
 No status was received from the peer in closing.
#defineWS_STATUS_OK   1000
 Normal closure.
#defineWS_STATUS_POLICY_VIOLATION   1008
 Application level policy violation.
#defineWS_STATUS_PROTOCOL_ERROR   1002
 WebSockets protocol error.
#defineWS_STATUS_TLS_ERROR   1015
 TLS handshake error.
#defineWS_STATUS_UNSUPPORTED_TYPE   1003
 Unsupported message data type.
#defineWS_VERSION   13
 Current WebSocket specification version.

Typedefs

typedef void(* WebSocketProc) (struct WebSocket *webSocket, int event, cchar *buf, ssize len, void *arg)

WebSocket callback procedure invoked when a message is received or the connection is first opened.

Parameters:
webSocketWebSocket object.
eventEvent type.
bufMessage buffer holding the message data. On open and close, the buffer is NULL and the length is 0.
lenLength of the message.
argUser argument.

WebSocket

WebSocket WebSockets RFC 6455 implementation for client and server communications.

Description:
WebSockets is a technology providing interactive communication between a server and client. Normal HTML connections follow a request / response paradigm and do not easily support asynchronous communications or unsolicited data pushed from the server to the client. WebSockets solves this by supporting bi-directional, full-duplex communications over persistent connections. A WebSocket connection is established over a standard HTTP connection and is then upgraded without impacting the original connection. This means it will work with existing networking infrastructure including firewalls and proxies.
Fields:
REventabortEvent Event for connection abortion.
RBuf *buf Buffer for accumulating incoming data.
WebSocketProccallback Event callback function for messages.
void *callbackArg User argument passed to callback.
intclient True if client, false if server.
char *clientKey Unique client identifier key.
char *closeReason UTF-8 reason text for connection closure.
intcloseStatus Close status code provided by peer.
intclosing Connection closing sequence has started.
void *data User-defined private data reference.
uchardataMask[4] Data masking key for frame processing.
Ticksdeadline Timeout deadline for next I/O operation.
interror Error code for last operation.
char *errorMessage Error message text for last operation.
RFiber *fiber Fiber context waiting for close.
intfin Final frame indicator for received packet.
intframe Current message frame processing state.
ssizeframeLength Length of current frame being processed.
intinCallback Currently executing in callback function.
intmaskOffset Current offset in data masking array.
ssizemaxFrame Maximum frame size in bytes.
ssizemaxMessage Maximum message size in bytes.
ssizemaxPacket Maximum packet size in bytes.
ssizemessageLength Total length of current message.
intneedFreeWebSocket object requires cleanup.
intopcode Opcode of current received message.
void *parent User-defined parent object reference.
intpartialUTF Last frame contained partial UTF-8 sequence.
REventpingEvent Timer event for ping transmission.
TimepingPeriod Interval for sending ping frames.
char *protocol Selected WebSocket sub-protocol.
intrxSeq Incoming packet sequence number (debug).
RSocket *sock Underlying network socket.
intstate Current WebSocket protocol state.
inttxSeq Outgoing packet sequence number (debug).
inttype Accumulated message type for multi-frame messages.
intvalidate Enable UTF-8 validation for text messages.
API Stability:
Internal.

Functions

WebSocket * webSocketAlloc (RSocket *sock, bool client)

Allocate a new WebSocket object.

Description:
This routine allocates and initializes a new WebSocket object.
Parameters:
sockCommunication socket.
clientTrue if the instance is a client, false if it is a server.
Returns:
The new WebSocket object.
API Stability:
Evolving.

void webSocketAsync (WebSocket *ws, WebSocketProc callback, void *arg, RBuf *buf)

Configure WebSocket for asynchronous operation with callback.

Description:
This routine configures the WebSocket for asynchronous operation by setting the event callback function that will be invoked when messages are received or connection events occur. The callback will be called for open, message, error, and close events.
Parameters:
wsWebSocket object.
callbackCallback function to handle WebSocket events.
argUser argument passed to the callback function.
bufBuffer containing pre-read data that may have been received as part of reading the HTTP headers.
API Stability:
Evolving.

void webSocketFree (WebSocket *ws)

Free a WebSocket object.

Description:
This routine frees a WebSocket object allocated by webSocketAlloc.
Parameters:
wsWebSocket object.
API Stability:
Evolving.

cchar * webSocketGetClientKey (WebSocket *ws)

Get the client key.

Description:
The client key is a unique identifier for the client.
Parameters:
wsWebSocket object.
Returns:
The client key.
API Stability:
Evolving.

cchar * webSocketGetCloseReason (WebSocket *ws)

Get the close reason supplied by the peer.

Description:
The peer may supply a UTF8 messages reason for the closure.
Parameters:
wsWebSocket object.
Returns:
The UTF8 reason string supplied by the peer when closing the WebSocket
API Stability:
Evolving.

void * webSocketGetData (WebSocket *ws)

Get the WebSocket private data.

Description:
Get the private data defined with webSocketSetData.
Parameters:
wsWebSocket object.
Returns:
The private data reference.
API Stability:
Evolving.

cchar * webSocketGetErrorMessage (WebSocket *ws)

Get the error message for the current message.

Description:
The error message will be set if an error occurs while parsing or processing the message.
Parameters:
wsWebSocket object.
Returns:
The error message. Caller must not free the message.
API Stability:
Evolving.

ssize webSocketGetMessageLength (WebSocket *ws)

Get the message length for the current message.

Description:
The message length will be updated as the message frames are received. The message length is only complete when the last frame has been received.
Parameters:
wsWebSocket object.
Returns:
The size of the message.
API Stability:
Evolving.

bool webSocketGetOrderlyClosed (WebSocket *ws)

Test if WebSocket connection was orderly closed by sending an acknowledged close message.

Description:
Check whether the WebSocket connection was closed cleanly with proper close handshake sequence, as opposed to an abrupt disconnection.
Parameters:
wsWebSocket object.
Returns:
True if the WebSocket was orderly closed.
API Stability:
Evolving.

char * webSocketGetProtocol (WebSocket *ws)

Get the selected WebSocket protocol selected by the server.

Description:
Retrieve the WebSocket sub-protocol that was negotiated and selected during the handshake process.
Parameters:
wsWebSocket object.
Returns:
The WebSocket protocol string.
API Stability:
Evolving.

ssize webSocketGetState (WebSocket *ws)

Get the WebSocket state.

Description:
Get the current state of the WebSocket connection.
Parameters:
wsWebSocket object.
Returns:
The WebSocket state. Will be WS_STATE_CONNECTING, WS_STATE_OPEN, WS_STATE_CLOSING or WS_STATE_CLOSED.
API Stability:
Evolving.

int webSocketProcess (WebSocket *ws)

Process a packet of data containing webSocket frames and data.

Description:
This routine processes a WebSocket packet.
Parameters:
wsWebSocket object.
Returns:
0 on close, < 0 for error and 1 for message(s) received.
API Stability:
Evolving.

void webSocketSelectProtocol (WebSocket *ws, cchar *protocol)

Select the WebSocket protocol.

Description:
Select the WebSocket protocol for the WebSocket session.
Parameters:
wsWebSocket object.
protocolWebSocket protocol.
API Stability:
Evolving.

ssize webSocketSend (WebSocket *ws, cchar *fmt, ...)

Send a UTF-8 text message to the WebSocket peer.

Description:
This call invokes webSocketSend with a type of WS_MSG_TEXT. The message must be valid UTF8 as the peer will reject invalid UTF8 messages.
Parameters:
wsWebSocket object.
fmtPrintf style formatted string.
...Arguments for the format.
Returns:
Number of bytes written.
API Stability:
Evolving.

ssize webSocketSendBlock (WebSocket *ws, int type, cchar *msg, ssize len)

Send a message of a given type to the WebSocket peer.

Description:
This API permits control of message types and message framing.

This routine may block for up to the inactivity timeout if the outgoing socket is full. When blocked, other fibers will be allowed to run.

This API may split the message into frames such that no frame is larger than the limit "webSocketsFrameSize". However, if the type has the more flag set by oring the WEB_MORE define to indicate there is more data to complete this entire message, the data provided to this call will not be split into frames and will not be aggregated with previous or subsequent messages. i.e. frame boundaries will be preserved and sent as-is to the peer.

Parameters:
wsWebSocket object.
typeWeb socket message type. Choose from WS_MSG_TEXT, WS_MSG_BINARY or WS_MSG_PING. Do not send a WS_MSG_PONG message as it is generated internally by the Web Sockets module. Use webSocketSendClose to send a close message.
msgMessage data buffer to send.
lenLength of msg.
Returns:
Number of data message bytes written. Should equal len if successful, otherwise returns a negative error code.
API Stability:
Evolving.

ssize webSocketSendClose (WebSocket *ws, int status, cchar *reason)

Send a close message to the WebSocket peer.

Description:
This call invokes webSocketSendBlock with a type of WS_MSG_CLOSE. The status and reason are encoded in the message. The reason is an optional UTF8 closure reason message.
Parameters:
wsWebSocket object.
statusWeb socket status.
reasonOptional UTF8 reason text message. The reason must be less than 124 bytes in length.
Returns:
Number of data message bytes written. Should equal len if successful, otherwise returns a negative error code.
API Stability:
Evolving.

ssize webSocketSendJson (WebSocket *ws, Json *json, int nid, cchar *key)

Send a json object to the WebSocket peer.

Description:
This call invokes webSocketSendString with a type of WS_MSG_TEXT.
Parameters:
wsWebSocket object.
jsonJson object.
nidNode id.
keyKey.
Returns:
Number of bytes written.
API Stability:
Evolving.

ssize ssize webSocketSendString (WebSocket *ws, cchar *buf)

Send a string to the WebSocket peer.

Description:
This call invokes webSocketSendBlock with a type of WS_MSG_TEXT.
Parameters:
wsWebSocket object.
bufString to send.
Returns:
Number of bytes written.
API Stability:
Evolving.

void webSocketSetClientKey (WebSocket *ws, cchar *clientKey)

Set the client key.

Description:
Set the client key for the WebSocket object. This unique identifier is used during the WebSocket handshake process and for client identification.
Parameters:
wsWebSocket object.
clientKeyClient key string.
API Stability:
Evolving.

void webSocketSetData (WebSocket *ws, void *data)

Set the WebSocket private data.

Description:
Set private data to be retained by the garbage collector.
Parameters:
wsWebSocket object.
dataManaged data reference.
API Stability:
Evolving.

void webSocketSetFiber (WebSocket *ws, RFiber *fiber)

Set the WebSocket fiber.

Description:
Associate a fiber context with the WebSocket object for cooperative multitasking and blocking operations.
Parameters:
wsWebSocket object.
fiberFiber context to associate.
API Stability:
Evolving.

void webSocketSetLimits (WebSocket *ws, ssize maxFrame, ssize maxMessage)

Set the maximum frame size and message size.

Description:
Set the maximum frame size and message size for the WebSocket object.
Parameters:
wsWebSocket object.
maxFrameMaximum frame size.
maxMessageMaximum message size.
API Stability:
Evolving.

void webSocketSetPingPeriod (WebSocket *ws, Time pingPeriod)

Set the ping period.

Description:
Configure the interval at which ping frames are automatically sent to keep the connection alive and detect disconnections.
Parameters:
wsWebSocket object.
pingPeriodTime interval between ping frames.
API Stability:
Evolving.

void webSocketSetValidateUTF (WebSocket *ws, bool validateUTF)

Set whether to validate UTF8 codepoints.

Description:
Set whether to validate UTF8 codepoints for the WebSocket object.
Parameters:
wsWebSocket object.
validateUTFTrue to validate UTF8 codepoints, false otherwise.
API Stability:
Evolving.

int webSocketWait (WebSocket *ws, Time deadline)

Wait for the WebSocket connection to close.

Description:
Block the current fiber until the WebSocket connection is closed or the deadline expires. This function allows graceful shutdown handling by waiting for the peer to acknowledge closure.
Parameters:
wsWebSocket object.
deadlineDeadline for the operation.
Returns:
0 on close, < 0 for error and 1 for message(s) received.
API Stability:
Evolving.