Barracuda Application Server C/C++ Reference
Native APIs, integration guides, and platform interfaces
WebSockets

Detailed Description

The Lua socket library (including WebSockets) provides three modes: blocking, asynchronous, and non-blocking (cosockets).

The C WebSocket Server library provides one mode, the asynchronous mode. Asynchronous sockets means that receiving data is event driven and sending data is blocking (socket is in blocking mode). The concept of using asynchronous sockets is the same for Lua and C code thus consult the Lua documentation for an introduction to asynchronous sockets.

Each frame payload is limited to 65535 bytes. Fragmented messages are not supported. Client frames must be masked. Hold the dispatcher mutex when using this API from application threads; callbacks run under that mutex.

Example:

The Barracuda App Server SDK includes one example using this WebSocket library and a copy of the example is available on GitHub

SDK example directory: examples/C-WebSockets/

Classes

struct  WSSCB
 WebSocket Server Connection Callback Interface: provides an interface between your application and the WebSocket server. More...
 
struct  WSS
 WebSocket Server (WSS) More...
 

Macros

#define WSSCB_constructor(o, frame, close, ping)    (o)->frameFp=frame,(o)->closeFp=close,(o)->pingFp=ping
 Initialize callback storage. More...
 
#define WSS_write(o, data, len, isTxt)   WSS_rawWrite(o, data, len, isTxt?1:2)
 Send one complete, unmasked server frame using blocking transport writes. More...
 
#define WSS_isValid(o)   SoDispCon_isValid((SoDispCon*)o)
 Check the local transport handle. More...
 

Typedefs

typedef void(* WSSCB_Frame) (struct WSSCB *o, struct WSS *wss, void *data, int len, int text)
 Receive a complete unfragmented text or binary frame. More...
 
typedef void(* WSSCB_Ping) (struct WSSCB *o, struct WSS *wss, void *data, int len)
 Optional notification after the internal pong send attempt succeeds. More...
 
typedef void(* WSSCB_Close) (struct WSSCB *o, struct WSS *wss, int status)
 Notify closure after the underlying connection has been closed. More...
 
typedef struct WSSCB WSSCB
 WebSocket Server Connection Callback Interface: provides an interface between your application and the WebSocket server. More...
 
typedef struct WSS WSS
 WebSocket Server (WSS) More...
 

Functions

BA_API void WSS_constructor (WSS *o, WSSCB *cb, SoDisp *disp, int startSize, int expandSize)
 Initialize an unconnected WebSocket object. More...
 
BA_API void WSS_destructor (WSS *o)
 Close the transport and free receive storage, without a WebSocket close handshake or close callback. More...
 
BA_API int WSS_upgrade (WSS *o, HttpRequest *req)
 Perform the server handshake and take over the request's connection. More...
 
BA_API int WSS_connect (WSS *o, HttpConnection *con)
 Take an HTTP connection after its WebSocket handshake is complete. More...
 
BA_API int WSS_rawWrite (WSS *o, const void *data, int len, int opCode)
 Send one final server frame with a caller-selected opcode. More...
 
BA_API int WSS_close (WSS *o, int statusCode)
 Attempt to send a close frame, then close the transport immediately. More...
 
 WSSCB::WSSCB (WSSCB_Frame frameFp, WSSCB_Close closeFp, WSSCB_Ping pingFp=0)
 Provide your callback event functions. More...
 
 WSS::WSS (WSSCB *cb, SoDisp *disp, int startSize, int expandSize)
 Initialize an unconnected WebSocket object. More...
 
 WSS::~WSS ()
 Close the transport and free receive storage, without a WebSocket close handshake or close callback. More...
 
int WSS::upgrade (HttpRequest *req)
 Perform the server handshake and take over the request's connection. More...
 
int WSS::connect (HttpConnection *con)
 Take an HTTP connection after its WebSocket handshake is complete. More...
 
int WSS::write (const void *data, int len, bool isTxt)
 Send one complete, unmasked server frame using blocking transport writes. More...
 
int WSS::close (int statusCode=1000)
 Attempt to send a close frame, then close the transport immediately. More...
 
bool WSS::isValid ()
 Check the local transport handle. More...
 

Macro Definition Documentation

◆ WSS_isValid

#define WSS_isValid (   o)    SoDispCon_isValid((SoDispCon*)o)

Check the local transport handle.

Returns
True while a socket is locally valid, false after it is closed. True does not prove that the peer is still reachable or that a write will succeed.
Parameters
oRequired initialized WebSocket.

◆ WSS_write

#define WSS_write (   o,
  data,
  len,
  isTxt 
)    WSS_rawWrite(o, data, len, isTxt?1:2)

Send one complete, unmasked server frame using blocking transport writes.

Parameters
dataReadable payload buffer for this call; required for positive len.
lenPayload byte count, 0 through 65535. The caller must enforce this range.
isTxtTrue for UTF-8 text supplied by the application; false for binary.
Returns
Zero when sent, negative on transport failure. No partial byte count is returned. This call does not itself deliver the receive-side close callback.
Parameters
oRequired connected WebSocket.

◆ WSSCB_constructor

#define WSSCB_constructor (   o,
  frame,
  close,
  ping 
)     (o)->frameFp=frame,(o)->closeFp=close,(o)->pingFp=ping

Initialize callback storage.

Parameters
oRequired writable interface.
frameRequired WSSCB_Frame callback.
closeRequired WSSCB_Close callback.
pingOptional WSSCB_Ping callback, or NULL.

Typedef Documentation

◆ WSS

typedef struct WSS WSS

WebSocket Server (WSS)

◆ WSSCB

typedef struct WSSCB WSSCB

WebSocket Server Connection Callback Interface: provides an interface between your application and the WebSocket server.

The WebSocket Server connection calls the functions in this interface on "receive" events.

◆ WSSCB_Close

typedef void(* WSSCB_Close) (struct WSSCB *o, struct WSS *wss, int status)

Notify closure after the underlying connection has been closed.

Parameters
oRequired borrowed callback interface.
wssClosed WebSocket object. Its storage still belongs to the application; this callback may arrange destruction/cleanup.
statusPeer close code when supplied, zero for a close without a usable code, a locally generated protocol close code, or a negative transport/allocation error. A positive value is not proof that the peer initiated a graceful close. Explicit WSS::close() and destruction do not invoke this callback.

◆ WSSCB_Frame

typedef void(* WSSCB_Frame) (struct WSSCB *o, struct WSS *wss, void *data, int len, int text)

Receive a complete unfragmented text or binary frame.

Parameters
oRequired borrowed callback interface.
wssConnection delivering this callback.
dataBorrowed payload with a temporary trailing NUL, including for binary frames. Embedded NUL bytes are possible; use len.
lenPayload byte count, 0 through 65535, excluding the added NUL.
textTRUE for text, FALSE for binary. The parser does not validate UTF-8. Copy data needed after return. Do not destroy wss or reuse its receive buffer from this callback; the parser continues using them afterward.

◆ WSSCB_Ping

typedef void(* WSSCB_Ping) (struct WSSCB *o, struct WSS *wss, void *data, int len)

Optional notification after the internal pong send attempt succeeds.

Parameters
oRequired borrowed callback interface.
wssConnection delivering this callback.
dataBorrowed ping payload, or NULL for an empty ping. Not guaranteed NUL-terminated. Copy data needed after return.
lenPayload byte count, 0 through 125. Do not destroy wss or reuse its receive buffer during this callback.
Warning
The current automatic pong path does not correctly reproduce a nonempty ping payload. This implementation limitation is pending source repair.

Function Documentation

◆ close()

int WSS::close ( int  statusCode = 1000)

Attempt to send a close frame, then close the transport immediately.

Parameters
statusCodeWebSocket close status valid for transmission; defaults to
  1. Nonpositive values are also replaced with 1000. The caller supplies a valid 16-bit protocol value; this function does not validate it.
Returns
Zero if the socket was valid and is now closed, -1 if already invalid. Zero does not confirm that the close frame was sent or acknowledged; send errors are not returned. The close callback is not invoked.

◆ connect()

int WSS::connect ( HttpConnection *  con)

Take an HTTP connection after its WebSocket handshake is complete.

Parameters
conRequired live connection to move into this object. Ownership of the socket transfers, leaving con without it. An existing WSS socket is closed.
Returns
Zero on success, -1 if con has no valid socket. This call does not perform or verify the handshake; use upgrade() for normal request handling.

◆ isValid()

bool WSS::isValid ( )

Check the local transport handle.

Returns
True while a socket is locally valid, false after it is closed. True does not prove that the peer is still reachable or that a write will succeed.

◆ upgrade()

int WSS::upgrade ( HttpRequest *  req)

Perform the server handshake and take over the request's connection.

Parameters
reqRequired current uncommitted WebSocket upgrade request.
Returns
Zero on successful handoff, -1 on handshake or invalid-connection failure. A rejected handshake attempts HTTP 400, or HTTP 426 with Sec-WebSocket-Version: 13 for an otherwise valid unsupported version. See HttpRequest::wsUpgrade for the validation requirements. On success, further I/O belongs to WSS; do not continue ordinary HTTP response output.

◆ write()

int WSS::write ( const void *  data,
int  len,
bool  isTxt 
)

Send one complete, unmasked server frame using blocking transport writes.

Parameters
dataReadable payload buffer for this call; required for positive len.
lenPayload byte count, 0 through 65535. The caller must enforce this range.
isTxtTrue for UTF-8 text supplied by the application; false for binary.
Returns
Zero when sent, negative on transport failure. No partial byte count is returned. This call does not itself deliver the receive-side close callback.

◆ WSS()

WSS::WSS ( WSSCB *  cb,
SoDisp *  disp,
int  startSize,
int  expandSize 
)

Initialize an unconnected WebSocket object.

Parameters
cbRequired borrowed interface with non-NULL frame and close callbacks.
dispRequired borrowed dispatcher. Both dependencies must outlive wss.
startSizePositive initial receive-buffer capacity in bytes.
expandSizePositive growth increment in bytes; raised to startSize if smaller. The buffer grows to retain an entire frame before invoking frameFp. Storage is allocated as input arrives. Receive allocation failure reports E_MALLOC through closeFp.

◆ WSS_close()

BA_API int WSS_close ( WSS *  o,
int  statusCode 
)

Attempt to send a close frame, then close the transport immediately.

Parameters
statusCodeWebSocket close status valid for transmission; defaults to
  1. Nonpositive values are also replaced with 1000. The caller supplies a valid 16-bit protocol value; this function does not validate it.
Returns
Zero if the socket was valid and is now closed, -1 if already invalid. Zero does not confirm that the close frame was sent or acknowledged; send errors are not returned. The close callback is not invoked.
Parameters
oRequired initialized WebSocket.

◆ WSS_connect()

BA_API int WSS_connect ( WSS *  o,
HttpConnection *  con 
)

Take an HTTP connection after its WebSocket handshake is complete.

Parameters
conRequired live connection to move into this object. Ownership of the socket transfers, leaving con without it. An existing WSS socket is closed.
Returns
Zero on success, -1 if con has no valid socket. This call does not perform or verify the handshake; use upgrade() for normal request handling.
Parameters
oRequired initialized WebSocket.

◆ WSS_constructor()

BA_API void WSS_constructor ( WSS *  o,
WSSCB *  cb,
SoDisp *  disp,
int  startSize,
int  expandSize 
)

Initialize an unconnected WebSocket object.

Parameters
cbRequired borrowed interface with non-NULL frame and close callbacks.
dispRequired borrowed dispatcher. Both dependencies must outlive wss.
startSizePositive initial receive-buffer capacity in bytes.
expandSizePositive growth increment in bytes; raised to startSize if smaller. The buffer grows to retain an entire frame before invoking frameFp. Storage is allocated as input arrives. Receive allocation failure reports E_MALLOC through closeFp.
oRequired storage to initialize.

◆ WSS_destructor()

BA_API void WSS_destructor ( WSS *  o)

Close the transport and free receive storage, without a WebSocket close handshake or close callback.

Stop other users first; borrowed cb/disp remain alive.

Parameters
oRequired initialized WebSocket.

◆ WSS_rawWrite()

BA_API int WSS_rawWrite ( WSS *  o,
const void *  data,
int  len,
int  opCode 
)

Send one final server frame with a caller-selected opcode.

Parameters
oRequired connected WebSocket.
dataReadable payload buffer, required when len is positive.
lenByte count, 0 through 65535 for text/binary or 0 through 125 for control frames. The caller validates length and payload semantics.
opCodeValid WebSocket opcode, normally 1 text, 2 binary, 8 close, 9 ping, or 10 pong. The FIN bit is always set; no mask is added.
Returns
Zero on success, negative transport error. No partial count is returned. This low-level call performs no opcode, length, or UTF-8 validation.

◆ WSS_upgrade()

BA_API int WSS_upgrade ( WSS *  o,
HttpRequest *  req 
)

Perform the server handshake and take over the request's connection.

Parameters
reqRequired current uncommitted WebSocket upgrade request.
Returns
Zero on successful handoff, -1 on handshake or invalid-connection failure. A rejected handshake attempts HTTP 400, or HTTP 426 with Sec-WebSocket-Version: 13 for an otherwise valid unsupported version. See HttpRequest::wsUpgrade for the validation requirements. On success, further I/O belongs to WSS; do not continue ordinary HTTP response output.
Parameters
oRequired initialized WebSocket.

◆ WSSCB()

WSSCB::WSSCB ( WSSCB_Frame  frameFp,
WSSCB_Close  closeFp,
WSSCB_Ping  pingFp = 0 
)

Provide your callback event functions.

Parameters
frameFpRequired callback for a complete text/binary frame.
closeFpRequired closure callback.
pingFpOptional ping callback; NULL disables notification.

◆ ~WSS()

WSS::~WSS ( )

Close the transport and free receive storage, without a WebSocket close handshake or close callback.

Stop other users first; borrowed cb/disp remain alive.