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. | |
void | webSocketAsync(WebSocket *ws, WebSocketProc callback, void *arg, RBuf *buf) |
Configure WebSocket for asynchronous operation with callback. | |
void | webSocketFree(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. | |
ssize | webSocketGetMessageLength(WebSocket *ws) |
Get the message length for the current message. | |
bool | webSocketGetOrderlyClosed(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. | |
ssize | webSocketGetState(WebSocket *ws) |
Get the WebSocket state. | |
int | webSocketProcess(WebSocket *ws) |
Process a packet of data containing webSocket frames and data. | |
void | webSocketSelectProtocol(WebSocket *ws, cchar *protocol) |
Select the WebSocket protocol. | |
ssize | webSocketSend(WebSocket *ws, cchar *fmt, ...) PRINTF_ATTRIBUTE(2 |
Send a UTF-8 text message to the WebSocket peer. | |
ssize | webSocketSendBlock(WebSocket *ws, int type, cchar *msg, ssize len) |
Send a message of a given type to the WebSocket peer. | |
ssize | webSocketSendClose(WebSocket *ws, int status, cchar *reason) |
Send a close message to the WebSocket peer. | |
ssize | webSocketSendJson(WebSocket *ws, Json *json, int nid, cchar *key) |
Send a json object to the WebSocket peer. | |
ssize ssize | webSocketSendString(WebSocket *ws, cchar *buf) |
Send a string to the WebSocket peer. | |
void | webSocketSetClientKey(WebSocket *ws, cchar *clientKey) |
Set the client key. | |
void | webSocketSetData(WebSocket *ws, void *data) |
Set the WebSocket private data. | |
void | webSocketSetFiber(WebSocket *ws, RFiber *fiber) |
Set the WebSocket fiber. | |
void | webSocketSetLimits(WebSocket *ws, ssize maxFrame, ssize maxMessage) |
Set the maximum frame size and message size. | |
void | webSocketSetPingPeriod(WebSocket *ws, Time pingPeriod) |
Set the ping period. | |
void | webSocketSetValidateUTF(WebSocket *ws, bool validateUTF) |
Set whether to validate UTF8 codepoints. | |
int | webSocketWait(WebSocket *ws, Time deadline) |
Wait for the WebSocket connection to close. |
Typedef Index
WebSocket | WebSocket WebSockets RFC 6455 implementation for client and server communications. |
WebSocketProc | WebSocket callback procedure invoked when a message is received or the connection is first opened. |
Defines
#define | WEB_MORE 0x1000 |
Flag for webSocketSendBlock to indicate there are more frames for this message. | |
#define | WS_CLIENT 1 |
Instance executing as a client. | |
#define | WS_EVENT_CLOSE 4 |
WebSocket connection is closed. | |
#define | WS_EVENT_ERROR 3 |
WebSocket error is detected. | |
#define | WS_EVENT_MESSAGE 1 |
WebSocket full (or last part of) message is received. | |
#define | WS_EVENT_OPEN 0 |
WebSocket connection is open. | |
#define | WS_EVENT_PARTIAL_MESSAGE 2 |
WebSocket partial message is received. | |
#define | WS_MAX_CONTROL 125 |
Maximum bytes in control message. | |
#define | WS_MAX_FRAME 131072 |
Maximum frame size. | |
#define | WS_MAX_MESSAGE (1024 * 1024) |
Maximum message size, zero for no limit. | |
#define | WS_MSG_BINARY 0x2 |
webSendBlock type for binary messages. | |
#define | WS_MSG_CLOSE 0x8 |
webSendBlock type for close message. | |
#define | WS_MSG_CONT 0x0 |
Continuation of WebSocket message. | |
#define | WS_MSG_CONTROL 0x8 |
Start of control messages. | |
#define | WS_MSG_MAX 0xB |
Max message type for webSendBlock. | |
#define | WS_MSG_MORE 0x10 |
Use on first call to webSendBlock to indicate more data to follow. | |
#define | WS_MSG_PING 0x9 |
webSendBlock type for ping messages. | |
#define | WS_MSG_PONG 0xA |
webSendBlock type for pong messages. | |
#define | WS_MSG_TEXT 0x1 |
webSendBlock type for text messages. | |
#define | WS_SERVER 0 |
Instance executing as a server. | |
#define | WS_STATE_CLOSED 3 |
WebSocket is closed. | |
#define | WS_STATE_CLOSING 2 |
WebSocket is closing. | |
#define | WS_STATE_CONNECTING 0 |
WebSocket connection is being established. | |
#define | WS_STATE_OPEN 1 |
WebSocket handsake is complete and ready for communications. | |
#define | WS_STATUS_COMMS_ERROR 1006 |
TCP/IP communications error | |
#define | WS_STATUS_FRAME_TOO_LARGE 1004 |
Reserved. | |
#define | WS_STATUS_GOING_AWAY 1001 |
Endpoint is going away. | |
#define | WS_STATUS_INTERNAL_ERROR 1011 |
Server terminating due to an internal error. | |
#define | WS_STATUS_INVALID_UTF8 1007 |
Text message has invalid UTF-8. | |
#define | WS_STATUS_MAX 5000 |
Maximum error status (less one). | |
#define | WS_STATUS_MESSAGE_TOO_LARGE 1009 |
Message is too large. | |
#define | WS_STATUS_MISSING_EXTENSION 1010 |
Unsupported WebSockets extension. | |
#define | WS_STATUS_NO_STATUS 1005 |
No status was received from the peer in closing. | |
#define | WS_STATUS_OK 1000 |
Normal closure. | |
#define | WS_STATUS_POLICY_VIOLATION 1008 |
Application level policy violation. | |
#define | WS_STATUS_PROTOCOL_ERROR 1002 |
WebSockets protocol error. | |
#define | WS_STATUS_TLS_ERROR 1015 |
TLS handshake error. | |
#define | WS_STATUS_UNSUPPORTED_TYPE 1003 |
Unsupported message data type. | |
#define | WS_VERSION 13 |
Current WebSocket specification version. |
Typedefs
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:
REvent abortEvent Event for connection abortion. RBuf * buf Buffer for accumulating incoming data. WebSocketProc callback Event callback function for messages. void * callbackArg User argument passed to callback. int client True if client, false if server. char * clientKey Unique client identifier key. char * closeReason UTF-8 reason text for connection closure. int closeStatus Close status code provided by peer. int closing Connection closing sequence has started. void * data User-defined private data reference. uchar dataMask[4] Data masking key for frame processing. Ticks deadline Timeout deadline for next I/O operation. int error Error code for last operation. char * errorMessage Error message text for last operation. RFiber * fiber Fiber context waiting for close. int fin Final frame indicator for received packet. int frame Current message frame processing state. ssize frameLength Length of current frame being processed. int inCallback Currently executing in callback function. int maskOffset Current offset in data masking array. ssize maxFrame Maximum frame size in bytes. ssize maxMessage Maximum message size in bytes. ssize maxPacket Maximum packet size in bytes. ssize messageLength Total length of current message. int needFree WebSocket object requires cleanup. int opcode Opcode of current received message. void * parent User-defined parent object reference. int partialUTF Last frame contained partial UTF-8 sequence. REvent pingEvent Timer event for ping transmission. Time pingPeriod Interval for sending ping frames. char * protocol Selected WebSocket sub-protocol. int rxSeq Incoming packet sequence number (debug). RSocket * sock Underlying network socket. int state Current WebSocket protocol state. int txSeq Outgoing packet sequence number (debug). int type Accumulated message type for multi-frame messages. int validate Enable UTF-8 validation for text messages.
- API Stability:
- Internal.
Functions
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:
ws WebSocket object. callback Callback function to handle WebSocket events. arg User argument passed to the callback function. buf Buffer containing pre-read data that may have been received as part of reading the HTTP headers.
- API Stability:
- Evolving.
Get the client key.
- Description:
- The client key is a unique identifier for the client.
- Parameters:
ws WebSocket object.
- Returns:
- The client key.
- API Stability:
- Evolving.
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:
ws WebSocket object.
- Returns:
- The error message. Caller must not free the message.
- API Stability:
- Evolving.
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:
ws WebSocket object.
- Returns:
- The size of the message.
- API Stability:
- Evolving.
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:
ws WebSocket object.
- Returns:
- True if the WebSocket was orderly closed.
- API Stability:
- Evolving.
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:
ws WebSocket object. fmt Printf style formatted string. ... Arguments for the format.
- Returns:
- Number of bytes written.
- API Stability:
- Evolving.
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:
ws WebSocket object. type Web 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. msg Message data buffer to send. len Length of msg.
- Returns:
- Number of data message bytes written. Should equal len if successful, otherwise returns a negative error code.
- API Stability:
- Evolving.
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:
ws WebSocket object. status Web socket status. reason Optional 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.
Set the ping period.
- Description:
- Configure the interval at which ping frames are automatically sent to keep the connection alive and detect disconnections.
- Parameters:
ws WebSocket object. pingPeriod Time interval between ping frames.
- API Stability:
- Evolving.
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:
ws WebSocket object. deadline Deadline for the operation.
- Returns:
- 0 on close, < 0 for error and 1 for message(s) received.
- API Stability:
- Evolving.