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.
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, RBuf *packet, WebSocketProc callback, void *arg, Time deadline)
 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.
voidwebSocketSetClientKey(WebSocket *ws, cchar *clientKey)
 Set the client key.
voidwebSocketSetData(WebSocket *ws, void *data)
 Set the WebSocket private data.
voidwebSocketSetLimits(WebSocket *ws, ssize maxFrame, ssize maxMessage)
 Set the maximum frame size and message size.
voidwebSocketSetPingPeriod(WebSocket *ws, Time pingPeriod)
 Set the ping period.
voidwebSocketSetProtocols(WebSocket *ws, cchar *protocols)
 Set a list of application-level protocols supported by the client.
voidwebSocketSetValidateUTF(WebSocket *ws, bool validateUTF)
 Set whether to validate UTF8 codepoints.

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_MAX_CONTROL   125
 Maximum bytes in control message.
#defineWS_MAX_FRAME   131072
 Maximum frame size.
#defineWS_MAX_MESSAGE   MAXINT
 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, cchar *buf, ssize len, void *arg)

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

Parameters:
webSocketWebSocket object.
bufMessage buffer holding the message data. On open, 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:
void *callbackArg Open and read event callback.
intclient Client or server.
char *clientKey Client key.
char *closeReason Reason for closure.
intcloseStatus Close status provided by peer.
intclosing Started closing sequnce.
void *data Custom data for applications.
uchardataMask[4] Mask for data.
Ticksdeadline Timeout deadline for when the next I/O must complete.
interror Error code.
char *errorMessage Error message for last I/O.
intfin RX final packet.
intframe Message frame state.
ssizeframeLength Length of the current frame.
intmaskOffset Offset in dataMask.
ssizemaxFrame Maximum frame size.
ssizemaxMessage Maximum message size.
ssizemaxPacket Maximum packet size.
ssizemessageLength Length of the current message.
intopcode Rx message opcode.
intpartialUTF Last frame had a partial UTF codepoint.
REventpingEvent Ping timer event.
TimepingPeriod Ping period.
char *protocol Selected protocol.
char *protocols Server supported protocols.
intrxSeq Incoming packet number (debug only).
RSocket *sock Communication socket.
intstate Protocol State.
inttxSeq Outgoing packet number (debug only).
inttype Rx message accumulated type.
intvalidate Validate UTF8 codepoints.
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:
Prototype.

void webSocketFree (WebSocket *ws)

Free a WebSocket object.

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

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:
Prototype.

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:
Prototype.

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:
Prototype.

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 processingthe message.
Parameters:
wsWebSocket object.
Returns:
The error message. Caller must not free the message.
API Stability:
Prototype.

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:
Prototype.

bool webSocketGetOrderlyClosed (WebSocket *ws)

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

Parameters:
wsWebSocket object.
Returns:
True if the WebSocket was orderly closed.
API Stability:
Prototype.

char * webSocketGetProtocol (WebSocket *ws)

Get the selected WebSocket protocol selected by the server.

Parameters:
wsWebSocket object.
Returns:
The WebSocket protocol string.
API Stability:
Prototype.

ssize webSocketGetState (WebSocket *ws)

Get the WebSocket state.

Returns:
The WebSocket state. Will be WS_STATE_CONNECTING, WS_STATE_OPEN, WS_STATE_CLOSING or WS_STATE_CLOSED.
API Stability:
Prototype.

int webSocketProcess (WebSocket *ws, RBuf *packet, WebSocketProc callback, void *arg, Time deadline)

Process a packet of data containing webSocket frames and data.

Description:
This routine processes a WebSocket packet.
Parameters:
wsWebSocket object.
packetPacket buffer.
callbackUser callback invoked when the connection is first opened and when a message is received. On open, the buffer is NULL and the length is 0.
argUser argument.
deadlineDeadline for the operation. This is a time at which the I/O must be received.
Returns:
0 on success, negative error code on failure.

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:
Prototype.

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:
Prototype.

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 presserved 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:
Prototype.

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:
Prototype.

void webSocketSetClientKey (WebSocket *ws, cchar *clientKey)

Set the client key.

Description:
Set the client key for the WebSocket object. This is used to identify the client.
Parameters:
wsWebSocket object.
clientKeyClient key.
API Stability:
Prototype.

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:
Prototype.

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:
Prototype.

void webSocketSetPingPeriod (WebSocket *ws, Time pingPeriod)

Set the ping period.

Description:
Set the ping period for the WebSocket object.
Parameters:
wsWebSocket object.
pingPeriodPing period.
API Stability:
Prototype.

void webSocketSetProtocols (WebSocket *ws, cchar *protocols)

Set a list of application-level protocols supported by the client.

Parameters:
wsWebSocket object.
protocolsComma separated list of application-level protocols.
API Stability:
Prototype.

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:
Prototype.