NetBurner 3.5.6
PDF Version |
WebSocket connection management class. More...
#include <websockets.h>
Public Member Functions | |
int | WriteData (const char *buf, int nbytes) |
Write data to the WebSocket connection. | |
int | ReadData (char *buf, int nbytes) |
Read data from the WebSocket connection. | |
void | Flush () |
Flush buffered transmit data to the network. | |
void | Pong (uint32_t len) |
Send a pong frame in response to a ping. | |
WS_State | GetState () |
Get the current connection state of the WebSocket. | |
int | Ping (uint32_t len, uint32_t *sentTick) |
Send a WebSocket ping frame and record the timestamp. | |
int | WaitForPingReply (uint32_t timeout) |
Block waiting for a pong reply to a previously sent ping. | |
int | GetPingReplyTick (uint32_t *replyTick) |
Get the tick count when the last pong was received. | |
int | setoption (int option) |
Set a socket option on this WebSocket connection. | |
int | clroption (int option) |
Clear a socket option on this WebSocket connection. | |
int | getoption () |
Get the current socket options bitmap. | |
int | GetWriteSpace () |
Get available transmit buffer space in bytes. | |
void | DumpSock () |
Dump detailed state information for this WebSocket connection. | |
Static Public Member Functions | |
static int | ws_readwto (int fd, char *buf, int nbytes, int timeout) |
Read data from a WebSocket connection with timeout. | |
static int | ws_read (int fd, char *buf, int nbytes) |
Read data from a WebSocket connection. | |
static int | ws_write (int fd, const char *buf, int nbytes) |
Write data to a WebSocket connection. | |
static int | ws_externalclose (int fd) |
Close a WebSocket connection from an external caller. | |
static void | ws_flush (int fd) |
Flush the transmit buffer of a WebSocket connection. | |
static int | ws_setoption (int fd, int option) |
Set a socket option on a WebSocket connection. | |
static int | ws_clroption (int fd, int option) |
Clear a socket option on a WebSocket connection. | |
static int | ws_getoption (int fd) |
Get the current socket options for a WebSocket connection. | |
static WebSocket * | GetWebSocketRecord (int fd) |
Find a WebSocket record by its file descriptor. | |
static int | promote_tcp_ws (int tcp_fd) |
Promote a TCP socket to a WebSocket connection after successful handshake. | |
static void | ws_read_notify (int fd) |
TCP read notification callback invoked when data is available on the WebSocket. | |
static void | ws_write_notify (int fd) |
TCP write notification callback invoked when buffer space becomes available. | |
static void | GetFlushTime () |
Updates the global flush timing for WebSocket message delivery. | |
static void | RunSkippedCallBack () |
Executes the callback function when a scheduled run is skipped. | |
static int | Connect (const char *host, const char *resource, const char *protocol, int portnum=80, bool useSSL=false) |
Connect to a WebSocket server using hostname with optional protocol negotiation. | |
static int | Connect (const char *host, const char *resource, int portnum=80, bool useSSL=false) |
Connect to a WebSocket server using hostname without protocol negotiation. | |
static int | Connect (IPADDR host, const char *resource, const char *protocol, int portnum=80, bool useSSL=false) |
Connect to a WebSocket server using IP address with optional protocol negotiation. | |
static int | Connect (IPADDR host, const char *resource, int portnum=80, bool useSSL=false) |
Connect to a WebSocket server using IP address without protocol negotiation. | |
static void | DumpSockets () |
Dump detailed state information for all active WebSocket connections. | |
static int | GetFreeWebSocketCount () |
Get the number of available WebSocket connection slots. | |
Public Attributes | |
int | m_fd_tcp |
TCP socket file descriptor (underlying transport) | |
int | m_fd_ws |
WebSocket file descriptor (application-level identifier) | |
OS_CRIT | socket_crit |
Critical section for thread-safe socket operations. | |
Static Public Attributes | |
static int | s_openSocketCount |
Number of currently open WebSocket connections. | |
static WebSocket | WSSockStructs [WS_MAX_SOCKS] |
Static array of WebSocket connection structures. | |
WebSocket connection management class.
Handles WebSocket protocol implementation including frame parsing, connection state, and bidirectional communication over TCP. Supports both client and server roles.
{
int NB::WebSocket::clroption | ( | int | option | ) |
Clear a socket option on this WebSocket connection.
option | The socket option to clear (e.g., WS_SO_TEXT, TCP_NODELAY, SO_KEEPALIVE) |
This member function clears (disables) a specific socket option on the WebSocket connection. It is the counterpart to setoption() and allows you to disable previously enabled options or ensure certain options are not active.
Clearing an option returns the socket to its default behavior for that particular setting. This is useful when you need to:
Clearing an option that was never set has no effect and typically succeeds.
Expand for Example Usage
|
static |
Connect to a WebSocket server using hostname with optional protocol negotiation.
Establishes a WebSocket client connection to the specified server by hostname, performing DNS resolution, TCP connection, HTTP upgrade handshake, and optional subprotocol negotiation. This is the primary method for creating client-side WebSocket connections.
host | Hostname or domain name of the WebSocket server (e.g., "ws.example.com"). Must be a null-terminated string. DNS resolution is performed automatically. |
resource | WebSocket endpoint path (e.g., "/api/v1/stream", "/ws", "/chat"). Must start with "/" and be null-terminated. This is the path portion of the WebSocket URL. |
protocol | Optional subprotocol to negotiate (e.g., "chat", "mqtt", "json"). Pass NULL for no subprotocol negotiation. If specified, the server must support and accept this protocol during the handshake. |
portnum | TCP port number for the WebSocket connection (default: 80 for ws://, 443 for wss://). Standard ports are 80 (unencrypted) and 443 (SSL/TLS). |
useSSL | Set true to use WebSocket Secure (wss://) with TLS encryption, false for unencrypted WebSocket (ws://). Default is false. |
Returns a WebSocket file descriptor on success (positive integer), or a negative value on failure:
Common failure scenarios:
Expand for Example Usage
|
inlinestatic |
Connect to a WebSocket server using hostname without protocol negotiation.
Convenience overload that establishes a WebSocket client connection without specifying a subprotocol. This is the most common connection method as many WebSocket servers don't require subprotocol negotiation.
host | Hostname or domain name of the WebSocket server (e.g., "ws.example.com") |
resource | WebSocket endpoint path (e.g., "/ws", "/api/stream") |
portnum | TCP port number (default: 80 for ws://, 443 for wss://) |
useSSL | Set true for wss:// (encrypted), false for ws:// (default: false) |
Returns WebSocket file descriptor (positive) on success, negative on failure.
|
static |
Connect to a WebSocket server using IP address with optional protocol negotiation.
Establishes a WebSocket client connection using a direct IP address, bypassing DNS resolution. This is useful for local networks, static IPs, or when DNS is unavailable. Otherwise identical to the hostname-based Connect method.
host | IP address of the WebSocket server as IPADDR type. Can be constructed using AsciiToIp() for dotted notation or direct IP address types. Example: AsciiToIp("192.168.1.100") or IPADDR(192,168,1,100) |
resource | WebSocket endpoint path (e.g., "/api/v1/stream", "/ws") |
protocol | Optional subprotocol to negotiate (NULL for none) |
portnum | TCP port number (default: 80 for ws://, 443 for wss://) |
useSSL | Set true for wss:// (encrypted), false for ws:// (default: false) |
Returns WebSocket file descriptor (positive) on success, negative on failure.
Expand for Example Usage
|
inlinestatic |
Connect to a WebSocket server using IP address without protocol negotiation.
Convenience overload that establishes a WebSocket client connection using an IP address without specifying a subprotocol. Most commonly used for local network connections or when the server doesn't require protocol negotiation.
host | IP address of the WebSocket server (IPADDR type) |
resource | WebSocket endpoint path (e.g., "/ws", "/api/stream") |
portnum | TCP port number (default: 80 for ws://, 443 for wss://) |
useSSL | Set true for wss:// (encrypted), false for ws:// (default: false) |
Returns WebSocket file descriptor (positive) on success, negative on failure.
void NB::WebSocket::DumpSock | ( | ) |
Dump detailed state information for this WebSocket connection.
Prints comprehensive diagnostic information about the current WebSocket connection to the debug console, including connection state, buffer levels, file descriptors, timing information, and internal state variables. Useful for debugging connection issues, buffer management, and protocol state.
Typical output includes:
Expand for Example Usage
|
static |
Dump detailed state information for all active WebSocket connections.
Prints comprehensive diagnostic information for all WebSocket connections in the WSSockStructs array to the debug console. This includes both active and inactive slots, showing the overall state of the WebSocket subsystem. Useful for system-wide debugging and monitoring.
For each WebSocket slot (0 to WS_MAX_SOCKS-1):
Expand for Example Usage
void NB::WebSocket::Flush | ( | ) |
Flush buffered transmit data to the network.
This member function forces any pending data in the WebSocket's transmit buffer to be sent immediately to the peer over the network. Normally, the WebSocket implementation may buffer small amounts of data to optimize network usage through packet coalescing, but this function overrides that behavior to ensure immediate transmission.
The flush operation is essential for:
The function blocks until the buffer contents have been passed to the underlying TCP/IP stack, though actual network transmission depends on network conditions and the peer's receive capability.
Expand for Example Usage
|
static |
Updates the global flush timing for WebSocket message delivery.
This static function updates timing-related variables that control when buffered WebSocket messages should be flushed to the network. It helps optimize message batching and delivery by determining appropriate flush intervals based on system conditions, message priorities, or application requirements.
Common timing strategies include:
If timing variables are accessed from multiple contexts, appropriate synchronization must be used.
Expand for Example Usage
|
static |
Get the number of available WebSocket connection slots.
Returns the count of free (unused) WebSocket connection slots available for new connections. This is useful for checking resource availability before attempting to create new connections, preventing "no slots available" errors.
Returns the number of free connection slots (0 to WS_MAX_SOCKS):
Expand for Example Usage
int NB::WebSocket::getoption | ( | ) |
Get the current socket options bitmap.
This member function retrieves the current state of all socket options for this WebSocket connection. It returns a bitmask where each bit represents a specific socket option's state (enabled/disabled).
The returned value can be tested against specific option flags using bitwise AND operations to determine if particular options are currently enabled.
Common uses include:
Example option flags that may be present in the bitmask:
Expand for Example Usage
int NB::WebSocket::GetPingReplyTick | ( | uint32_t * | replyTick | ) |
Get the tick count when the last pong was received.
replyTick | Pointer to variable to receive the tick count of last pong reception |
This function retrieves the system tick count (from TimeTick) at the moment the most recent pong frame was received. This timestamp can be used in conjunction with the ping send timestamp from Ping() to calculate precise round-trip time.
The function is useful for:
The returned tick count represents the absolute system time when the pong was received. Subtract the ping send tick (from Ping()) to get elapsed ticks, then convert to milliseconds using TICKS_PER_SECOND:
RTT_ms = ((replyTick - sentTick) * 1000) / TICKS_PER_SECOND
Expand for Example Usage
|
inline |
Get the current connection state of the WebSocket.
This inline function returns the current state of the WebSocket connection. The state indicates where the connection is in its lifecycle, from initial handshake through active communication to closure.
Common WebSocket states include:
Additional states may include:
Monitoring the state is essential for:
Expand for Example Usage
|
static |
Find a WebSocket record by its file descriptor.
fd | The WebSocket file descriptor to search for |
This function searches through the internal WebSocket registry to locate a WebSocket instance associated with the given file descriptor. It is typically used internally by the WebSocket management system to retrieve the WebSocket object for operations on an active connection.
Expand for Example Usage
|
inline |
Get available transmit buffer space in bytes.
This inline function returns the amount of free space currently available in the WebSocket's transmit (TX) buffer. The value indicates how many bytes can be written to the buffer before it becomes full.
This function is useful for:
The available space decreases as data is written to the buffer and increases as buffered data is transmitted over the network. The total buffer capacity is fixed at initialization.
Expand for Example Usage
int NB::WebSocket::Ping | ( | uint32_t | len, |
uint32_t * | sentTick ) |
Send a WebSocket ping frame and record the timestamp.
len | Length of optional ping payload data (typically 0 for standard ping) |
sentTick | Pointer to variable to receive the tick count when ping was sent |
This function sends a WebSocket ping control frame to the peer and records the system tick count at the time of transmission. Ping frames are used to:
The ping frame may optionally include payload data (up to 125 bytes per WebSocket specification), though a zero-length ping is most common. The peer should respond with a pong frame containing the same payload.
The sentTick parameter receives the system tick count (from TimeTick) at the moment the ping was sent. This timestamp can be used to calculate round-trip time when the corresponding pong is received.
Expand for Example Usage
void NB::WebSocket::Pong | ( | uint32_t | len | ) |
Send a pong frame in response to a ping.
len | Length of pong payload data (should match the ping payload length) |
This member function sends a WebSocket pong control frame, typically in response to a received ping frame from the peer. According to the WebSocket protocol (RFC 6455), when a ping is received, the endpoint must respond with a pong containing the same payload data.
Pong frames serve multiple purposes:
The WebSocket implementation typically handles ping frames automatically and sends pong responses without application intervention. However, this function allows manual pong transmission if needed for:
The length parameter should match the payload length of the ping being responded to. Most pings have zero-length payloads, so len=0 is most common. The maximum payload length for control frames is 125 bytes per the WebSocket specification.
Expand for Example Usage
|
static |
Promote a TCP socket to a WebSocket connection after successful handshake.
tcp_fd | The TCP socket file descriptor to promote |
This function converts an existing TCP connection into a WebSocket connection after the WebSocket handshake has been completed. It performs the necessary protocol upgrade and registers the connection in the WebSocket management system.
The promotion process typically involves:
Expand for Example Usage
int NB::WebSocket::ReadData | ( | char * | buf, |
int | nbytes ) |
Read data from the WebSocket connection.
buf | Pointer to buffer where received data will be stored |
nbytes | Maximum number of bytes to read into the buffer |
This member function reads data from the WebSocket connection into the provided buffer. It handles WebSocket frame decoding automatically, presenting the application data to the caller without protocol overhead.
Key characteristics:
The function operates in non-blocking mode:
Return value interpretation:
Expand for Example Usage
|
static |
Executes the callback function when a scheduled run is skipped.
This static function is invoked when a scheduled task or operation cannot be executed at its intended time (e.g., due to system overload, timing conflicts, or the previous execution still running). It allows the system to handle skip events gracefully by notifying registered handlers.
Implementation should be thread-safe if called from multiple scheduler contexts.
Expand for Example Usage
int NB::WebSocket::setoption | ( | int | option | ) |
Set a socket option on this WebSocket connection.
option | The socket option to set (e.g., WS_SO_TEXT, WS_SO_BINARY, SO_KEEPALIVE, TCP_NODELAY) |
This member function sets a specific socket option on the WebSocket connection. Options control various aspects of the WebSocket behavior and the underlying TCP socket configuration.
Common WebSocket-specific options:
Common TCP socket options:
Options can be combined using bitwise OR to set multiple options simultaneously. Setting an already-set option has no adverse effect.
Expand for Example Usage
int NB::WebSocket::WaitForPingReply | ( | uint32_t | timeout | ) |
Block waiting for a pong reply to a previously sent ping.
timeout | Timeout value in system ticks (use TICKS_PER_SECOND for conversion) |
This function blocks the calling task until a pong frame is received in response to a previously sent ping, or until the specified timeout expires. It is typically called immediately after Ping() to wait for the peer's response.
The function is useful for:
The timeout parameter is specified in system ticks. Use TICKS_PER_SECOND to convert from seconds:
Return value interpretation:
Expand for Example Usage
int NB::WebSocket::WriteData | ( | const char * | buf, |
int | nbytes ) |
Write data to the WebSocket connection.
buf | Pointer to buffer containing data to write |
nbytes | Number of bytes to write from the buffer |
This member function writes data to the WebSocket connection with automatic frame encoding. The function handles the WebSocket protocol overhead, allowing the application to send raw data that will be properly framed for transmission.
Key characteristics:
The function operates according to the WebSocket options set via setoption():
Return value interpretation:
Expand for Example Usage
|
static |
Clear a socket option on a WebSocket connection.
fd | The WebSocket file descriptor |
option | The socket option to clear (e.g., SO_KEEPALIVE, TCP_NODELAY) |
This static wrapper function clears (disables) a specific socket option on the underlying socket associated with the WebSocket connection. It is the counterpart to ws_setoption() and allows you to disable previously enabled options.
Clearing an option returns the socket to its default behavior for that particular setting. This is useful when you need to dynamically adjust socket behavior based on runtime conditions or when reverting configuration changes.
Expand for Example Usage
|
static |
Close a WebSocket connection from an external caller.
fd | The WebSocket file descriptor to close |
This static wrapper function provides a mechanism to close a WebSocket connection from external code (outside the WebSocket class). It performs a clean shutdown of the WebSocket, including:
This function differs from a simple socket close() by properly handling the WebSocket protocol's closing handshake, ensuring graceful disconnection.
Expand for Example Usage
|
static |
Flush the transmit buffer of a WebSocket connection.
fd | The WebSocket file descriptor |
This static wrapper function forces any pending data in the WebSocket's transmit buffer to be sent immediately to the peer. Normally, the WebSocket implementation may buffer small amounts of data to optimize network usage, but this function ensures immediate transmission.
Common use cases include:
Expand for Example Usage
|
static |
Get the current socket options for a WebSocket connection.
fd | The WebSocket file descriptor |
This static wrapper function retrieves the current state of socket options for the underlying socket associated with the WebSocket connection. It returns a bitmask where each bit represents a specific socket option's state (enabled/disabled).
The returned value can be tested against specific option flags to determine if particular options are currently enabled. This is useful for:
Expand for Example Usage
|
static |
Read data from a WebSocket connection.
fd | The WebSocket file descriptor |
buf | Pointer to buffer where received data will be stored |
nbytes | Maximum number of bytes to read into the buffer |
This static wrapper function reads data from a WebSocket connection into the provided buffer. It handles WebSocket frame decoding automatically, presenting the application data to the caller without protocol overhead.
The function behavior includes:
Return value interpretation:
Expand for Example Usage
|
static |
TCP read notification callback invoked when data is available on the WebSocket.
This static callback function is invoked by the NetBurner TCP/IP stack when data becomes available to read on the WebSocket file descriptor. It handles incoming WebSocket frames, processes control frames (ping, pong, close), and delivers data frames to the application layer.
fd | The file descriptor of the TCP socket with available data |
SetSocketReadNotify()
or similarThis callback must handle:
Called from the network stack context. Ensure thread-safe access to shared resources.
Expand for Example Usage
|
static |
Read data from a WebSocket connection with timeout.
fd | The WebSocket file descriptor |
buf | Pointer to buffer where received data will be stored |
nbytes | Maximum number of bytes to read into the buffer |
timeout | Timeout value in system ticks (use TICKS_PER_SECOND for conversion) |
This static wrapper function reads data from a WebSocket connection with a specified timeout period. Unlike ws_read() which returns immediately if no data is available, this function will wait up to the specified timeout for data to arrive.
The timeout mechanism allows for:
Return value interpretation:
The timeout parameter is specified in system ticks. Use TICKS_PER_SECOND to convert from seconds:
Expand for Example Usage
|
static |
Set a socket option on a WebSocket connection.
fd | The WebSocket file descriptor |
option | The socket option to set (e.g., SO_KEEPALIVE, TCP_NODELAY) |
This static wrapper function sets a specific socket option on the underlying socket associated with the WebSocket connection. It provides a convenient interface to modify socket behavior without directly accessing the underlying TCP socket.
Common socket options include:
Expand for Example Usage
|
static |
Write data to a WebSocket connection.
fd | The WebSocket file descriptor |
buf | Pointer to buffer containing data to send |
nbytes | Number of bytes to write from the buffer |
This static wrapper function writes data to a WebSocket connection with automatic WebSocket frame encoding. The function handles the protocol overhead, allowing the application to send raw data that will be properly framed for WebSocket transmission.
The function behavior includes:
Return value interpretation:
Expand for Example Usage
|
static |
TCP write notification callback invoked when buffer space becomes available.
This static callback function is invoked by the NetBurner TCP/IP stack when the TCP send buffer has space available for writing. It allows the WebSocket handler to resume sending data that was previously blocked due to a full send buffer. This implements flow control for outbound WebSocket traffic.
fd | The file descriptor of the TCP socket with available buffer space |
SetSocketWriteNotify()
or similarThis callback enables proper flow control by:
Called from the network stack context. Ensure thread-safe access to write queues.
Expand for Example Usage
int NB::WebSocket::m_fd_tcp |
TCP socket file descriptor (underlying transport)
This member variable stores the file descriptor for the underlying TCP socket that provides the transport layer for the WebSocket connection. The TCP socket handles the actual network communication, while the WebSocket protocol operates on top of it.
Key characteristics:
The TCP socket is typically established through one of two methods:
After the WebSocket handshake completes, this socket is "promoted" to WebSocket mode, but the underlying TCP file descriptor remains the same and continues to handle the transport.
Common operations using this file descriptor:
Expand for Example Usage
int NB::WebSocket::m_fd_ws |
WebSocket file descriptor (application-level identifier)
This member variable stores an application-level file descriptor or identifier that represents this WebSocket connection. While m_fd_tcp represents the underlying TCP transport, m_fd_ws provides a WebSocket-specific identifier used by the WebSocket management system.
Key characteristics:
This identifier is used throughout the WebSocket API for operations such as:
In some implementations, m_fd_ws may equal m_fd_tcp, indicating the same file descriptor is used for both layers. In other implementations, they may be different to provide abstraction between layers.
Expand for Example Usage
|
static |
Number of currently open WebSocket connections.
This static member variable tracks the total number of active WebSocket connections currently managed by the WebSocket system. It is incremented when a new WebSocket connection is established and decremented when a connection is closed.
This counter is useful for:
The value ranges from 0 to WS_MAX_SOCKS (the maximum number of concurrent WebSocket connections supported by the system).
Expand for Example Usage
OS_CRIT NB::WebSocket::socket_crit |
Critical section for thread-safe socket operations.
This member variable provides a critical section (mutual exclusion) mechanism to ensure thread-safe access to the WebSocket's socket operations. In a multi-threaded RTOS environment, multiple tasks may attempt to read from, write to, or modify the same WebSocket connection simultaneously, which could lead to data corruption or protocol violations.
The critical section protects:
Usage pattern:
NetBurner RTOS provides OS_CRIT primitives for critical sections:
These operations disable task switching temporarily to ensure atomic execution of protected code sections. The critical section should be held for the minimum time necessary to avoid blocking other tasks.
Expand for Example Usage
|
static |
Static array of WebSocket connection structures.
This static array holds all WebSocket connection structures, providing storage for up to WS_MAX_SOCKS concurrent WebSocket connections. Each element represents a potential WebSocket connection slot.
The array is pre-allocated at compile time, eliminating the need for dynamic memory allocation during runtime. This approach:
When a new WebSocket connection is established, an unused slot in this array is assigned. When a connection closes, its slot becomes available for reuse.
Expand for Example Usage