http
April 7, 2026 ยท View on GitHub
{#httpmodule}
http
HTTP client/server, WebSocket support, form handling, cookies, URL parsing.
Namespaces
| Name | Description |
|---|---|
http | HTTP request/response types, parsers, and server/client helpers. |
ws | WebSocket framing, handshakes, and connection helpers. |
{#http}
http
HTTP request/response types, parsers, and server/client helpers.
Classes
| Name | Description |
|---|---|
Authenticator | Maintains HTTP Basic or Digest authentication state for outbound requests. |
BasicAuthenticator | Encodes and decodes HTTP Basic authentication credentials. |
ChunkedAdapter | HTTP chunked transfer encoding adapter for streaming responses. |
Client | HTTP client for creating and managing outgoing connections. |
ClientConnection | HTTP client connection for managing request/response lifecycle. |
Connection | Base HTTP connection managing socket I/O and message lifecycle |
ConnectionAdapter | Default HTTP socket adapter for reading and writing HTTP messages |
ConnectionPool | LIFO connection pool for reusing ServerConnection objects. Avoids per-request heap allocation by resetting and reusing connections instead of destroying and recreating them. |
ConnectionStream | Packet stream wrapper for an HTTP connection. |
Cookie | HTTP cookie value plus its response/header attributes. |
FilePart | Form part backed by a file on disk. |
FormPart | An implementation of FormPart. |
FormWriter | FormWriter is an HTTP client connection adapter for writing HTML forms. |
Message | The base class for Request and Response. |
MultipartAdapter | HTTP multipart encoding adapter for multipart/x-mixed-replace streaming. |
Parser | HTTP request/response parser using the llhttp library. |
ParserObserver | Abstract observer interface for HTTP parser events. |
ProgressSignal | HTTP progress signal for upload and download progress notifications. |
Request | HTTP request message with method, URI, headers, and optional body. |
Response | HTTP response message with status, reason phrase, headers, and body metadata. |
Server | HTTP server implementation. |
ServerConnection | HTTP server connection. |
ServerConnectionFactory | Factory for creating per-socket [ServerConnection](#serverconnection) and per-request [ServerResponder](#serverresponder) objects. |
ServerResponder | Base responder interface for handling one HTTP request on a server connection. Derived classes typically override [onRequest()](#onrequest) and optionally the streaming hooks. |
StringPart | Form part backed by an in-memory string payload. |
URL | An RFC 3986 based URL parser. Constructors and assignment operators will throw a SyntaxException if the URL is invalid. |
DateCache | Caches the formatted Date header, updated once per second. Avoids per-request time formatting and string allocation. |
Method | HTTP request methods. |
Enumerations
| Name | Description |
|---|---|
StatusCode | HTTP Response Status Codes. |
ServerConnectionState | HTTP server-side lifecycle phases used by the keep-alive state machine. |
ServerConnectionMode | Transport mode for server connections before and after protocol upgrade. |
{#statuscode}
StatusCode
enum StatusCode
HTTP Response Status Codes.
| Value | Description |
|---|---|
Continue | |
SwitchingProtocols | |
OK | |
Created | |
Accepted | |
NonAuthoritative | |
NoContent | |
ResetContent | |
PartialContent | |
MultipleChoices | |
MovedPermanently | |
Found | |
SeeOther | |
NotModified | |
UseProxy | |
TemporaryRedirect | |
BadRequest | |
Unauthorized | |
PaymentRequired | |
Forbidden | |
NotFound | |
MethodNotAllowed | |
NotAcceptable | |
ProxyAuthRequired | |
RequestTimeout | |
Conflict | |
Gone | |
LengthRequired | |
PreconditionFailed | |
EntityTooLarge | |
UriTooLong | |
UnsupportedMediaType | |
RangeNotSatisfiable | |
ExpectationFailed | |
UnprocessableEntity | |
UpgradeRequired | |
InternalServerError | |
NotImplemented | |
BadGateway | |
Unavailable | |
GatewayTimeout | |
VersionNotSupported |
{#serverconnectionstate}
ServerConnectionState
enum ServerConnectionState
HTTP server-side lifecycle phases used by the keep-alive state machine.
| Value | Description |
|---|---|
ReceivingHeaders | Parsing request headers. |
ReceivingBody | Receiving request body bytes. |
DispatchingOrSending | Dispatching the responder or sending a normal response. |
Streaming | Sending a long-lived streaming response. |
Upgraded | Upgraded to a non-HTTP protocol such as WebSocket. |
Closing | Close has been requested and teardown is in progress. |
Closed | Connection has fully closed. |
{#serverconnectionmode}
ServerConnectionMode
enum ServerConnectionMode
Transport mode for server connections before and after protocol upgrade.
| Value | Description |
|---|---|
Http | Standard HTTP request/response mode. |
Upgraded | Upgraded transport mode owned by another protocol adapter. |
Typedefs
| Return | Name | Description |
|---|---|---|
std::vector< ClientConnection::Ptr > | ClientConnectionPtrVec | List of owned client connections tracked by an HTTP client. |
{#clientconnectionptrvec}
ClientConnectionPtrVec
std::vector< ClientConnection::Ptr > ClientConnectionPtrVec()
List of owned client connections tracked by an HTTP client.
Functions
| Return | Name | Description |
|---|---|---|
bool | isBasicCredentials | Returns true if the given Authorization header value uses HTTP Basic authentication. |
bool | isDigestCredentials | Returns true if the given Authorization header value uses HTTP Digest authentication. |
bool | hasBasicCredentials | Returns true if the request contains a Basic Authorization header. |
bool | hasDigestCredentials | Returns true if the request contains a Digest Authorization header. |
bool | hasProxyBasicCredentials | Returns true if the request contains a Basic Proxy-Authorization header. |
bool | hasProxyDigestCredentials | Returns true if the request contains a Digest Proxy-Authorization header. |
void | extractCredentials | Splits a "user:password" user-info string into separate username and password strings. If no ':' is present, the entire string is treated as the username and password is empty. |
void | extractCredentials | Extracts username and password from the user-info component of a URL. Does nothing if the URL has no user-info part. |
ClientConnection::Ptr | createConnectionT inline | Creates a ClientConnection (or subtype) for the given URL without registering it with a Client instance. The socket and adapter are chosen based on the URL scheme: |
ClientConnection::Ptr | createConnection inline | Creates a ClientConnection for the given URL and optionally registers it with a Client. Equivalent to calling Client::createConnection() when client is non-null. |
const char * | getStatusCodeReason | Returns the standard reason phrase for the given HTTP status code (e.g. "OK" for StatusCode::OK, "Not Found" for StatusCode::NotFound). |
const char * | getStatusCodeString | Returns a combined "NNN Reason" string for the given HTTP status code (e.g. "200 OK"). |
std::string | parseURI | Extracts the URI (path and query) from a raw HTTP request line. |
bool | matchURL | Tests whether a URI matches a glob-style expression. |
std::string | parseCookieItem | Extracts a named attribute from a Cookie header value. |
bool | splitURIParameters | Parses URL query parameters from a URI into key-value pairs. Handles percent-decoding of names and values. |
void | splitParameters | Splits a header-style parameter string into a primary value and named attributes. Attributes are separated by ';'. Enclosing quotes are stripped from values. |
void | splitParameters | Splits a substring (defined by iterators) into named attributes. Attributes are separated by ';'. Enclosing quotes are stripped from values. |
{#isbasiccredentials}
isBasicCredentials
bool isBasicCredentials(std::string_view header)
Returns true if the given Authorization header value uses HTTP Basic authentication.
Parameters
headerValue of the Authorization or WWW-Authenticate header.
{#isdigestcredentials}
isDigestCredentials
bool isDigestCredentials(std::string_view header)
Returns true if the given Authorization header value uses HTTP Digest authentication.
Parameters
headerValue of the Authorization or WWW-Authenticate header.
{#hasbasiccredentials}
hasBasicCredentials
bool hasBasicCredentials(const http::Request & request)
Returns true if the request contains a Basic Authorization header.
Parameters
requestHTTP request to inspect.
{#hasdigestcredentials}
hasDigestCredentials
bool hasDigestCredentials(const http::Request & request)
Returns true if the request contains a Digest Authorization header.
Parameters
requestHTTP request to inspect.
{#hasproxybasiccredentials}
hasProxyBasicCredentials
bool hasProxyBasicCredentials(const http::Request & request)
Returns true if the request contains a Basic Proxy-Authorization header.
Parameters
requestHTTP request to inspect.
{#hasproxydigestcredentials}
hasProxyDigestCredentials
bool hasProxyDigestCredentials(const http::Request & request)
Returns true if the request contains a Digest Proxy-Authorization header.
Parameters
requestHTTP request to inspect.
{#extractcredentials}
extractCredentials
void extractCredentials(std::string_view userInfo, std::string & username, std::string & password)
Splits a "user:password" user-info string into separate username and password strings. If no ':' is present, the entire string is treated as the username and password is empty.
Parameters
-
userInfoInput string in the form "user:password". -
usernameReceives the extracted username. -
passwordReceives the extracted password.
{#extractcredentials-1}
extractCredentials
void extractCredentials(const http::URL & uri, std::string & username, std::string & password)
Extracts username and password from the user-info component of a URL. Does nothing if the URL has no user-info part.
Parameters
-
uriURL to extract credentials from. -
usernameReceives the extracted username. -
passwordReceives the extracted password.
{#createconnectiont}
createConnectionT
inline
template<class ConnectionT> inline ClientConnection::Ptr createConnectionT(const URL & url, uv::Loop * loop)
Creates a ClientConnection (or subtype) for the given URL without registering it with a Client instance. The socket and adapter are chosen based on the URL scheme:
-
"http" -> TCPSocket
-
"https" -> SSLSocket
-
"ws" -> TCPSocket + WebSocket adapter
-
"wss" -> SSLSocket + WebSocket adapter
Parameters
ConnectionTConcrete connection type derived from ClientConnection.
Parameters
-
urlTarget URL. Must have a recognised scheme. -
loopEvent loop to use. Defaults to the default libuv loop.
Returns
Shared pointer to the created connection.
Exceptions
std::runtime_errorif the URL scheme is not recognised.
{#createconnection}
createConnection
inline
inline ClientConnection::Ptr createConnection(const URL & url, http::Client * client, uv::Loop * loop)
Creates a ClientConnection for the given URL and optionally registers it with a Client. Equivalent to calling Client::createConnection() when client is non-null.
Parameters
-
urlTarget URL. The scheme determines the socket and adapter type. -
clientOptional Client instance to register the connection with. -
loopEvent loop to use. Defaults to the default libuv loop.
Returns
Shared pointer to the created connection.
{#getstatuscodereason}
getStatusCodeReason
const char * getStatusCodeReason(StatusCode status)
Returns the standard reason phrase for the given HTTP status code (e.g. "OK" for StatusCode::OK, "Not Found" for StatusCode::NotFound).
Parameters
statusHTTP status code.
Returns
Null-terminated reason phrase string.
{#getstatuscodestring}
getStatusCodeString
const char * getStatusCodeString(StatusCode status)
Returns a combined "NNN Reason" string for the given HTTP status code (e.g. "200 OK").
Parameters
statusHTTP status code.
Returns
Null-terminated status code string.
{#parseuri}
parseURI
std::string parseURI(std::string_view request)
Extracts the URI (path and query) from a raw HTTP request line.
Parameters
requestRaw HTTP request line (e.g. "GET /path?q=1 HTTP/1.1").
Returns
The URI portion (e.g. "/path?q=1").
{#matchurl}
matchURL
bool matchURL(std::string_view uri, std::string_view expression)
Tests whether a URI matches a glob-style expression.
Parameters
-
uriThe URI to test. -
expressionPattern to match against. '*' matches any sequence of characters.
Returns
true if the URI matches the expression.
{#parsecookieitem}
parseCookieItem
std::string parseCookieItem(std::string_view cookie, std::string_view item)
Extracts a named attribute from a Cookie header value.
Parameters
-
cookieFull Cookie header value (e.g. "name=value; Path=/; HttpOnly"). -
itemAttribute name to find (e.g. "Path").
Returns
The value of the named attribute, or an empty string if not found.
{#splituriparameters}
splitURIParameters
bool splitURIParameters(std::string_view uri, NVCollection & out)
Parses URL query parameters from a URI into key-value pairs. Handles percent-decoding of names and values.
Parameters
-
uriURI string optionally containing a '?' query component. -
outCollection to populate with parsed parameters.
Returns
true if at least one parameter was parsed; false otherwise.
{#splitparameters}
splitParameters
void splitParameters(const std::string & s, std::string & value, NVCollection & parameters)
Splits a header-style parameter string into a primary value and named attributes. Attributes are separated by ';'. Enclosing quotes are stripped from values.
Example input: "multipart/mixed; boundary="boundary-01234567"" Output value: "multipart/mixed", parameters: { "boundary" -> "boundary-01234567" }
Parameters
-
sInput string to split. -
valueReceives the primary value before the first ';'. -
parametersReceives the parsed attribute key-value pairs.
{#splitparameters-1}
splitParameters
void splitParameters(const std::string::const_iterator & begin, const std::string::const_iterator & end, NVCollection & parameters)
Splits a substring (defined by iterators) into named attributes. Attributes are separated by ';'. Enclosing quotes are stripped from values.
Parameters
-
beginIterator to the start of the string to parse. -
endIterator past the end of the string to parse. -
parametersReceives the parsed attribute key-value pairs.
{#authenticator}
Authenticator
#include <icy/http/authenticator.h>
Maintains HTTP Basic or Digest authentication state for outbound requests.
Note: Do not forget to read the entire response stream from the 401 response before sending the authenticated request, otherwise there may be problems if a persistent connection is used.
Public Methods
| Return | Name | Description |
|---|---|---|
Authenticator | Creates an empty authenticator. | |
Authenticator | Creates an authenticator with the given username and password. | |
~Authenticator | Destroys the authenticator. | |
void | fromUserInfo | Parses username:password std::string and sets username and password of the credentials object. Throws SyntaxException on invalid user information. |
void | fromURI | Extracts username and password from the given URI and sets username and password of the credentials object. Does nothing if URI has no user info part. |
void | setUsername | Sets the username. |
const std::string & | username const | Returns the username. |
void | setPassword | Sets the password. |
const std::string & | password const | Returns the password. |
void | authenticate | Inspects WWW-Authenticate header of the response, initializes the internal state (in case of digest authentication) and adds required information to the given http::Request. |
void | updateAuthInfo | Updates internal state (in case of digest authentication) and replaces authentication information in the request accordingly. |
void | proxyAuthenticate | Inspects Proxy-Authenticate header of the response, initializes the internal state (in case of digest authentication) and adds required information to the given http::Request. |
void | updateProxyAuthInfo | Updates internal state (in case of digest authentication) and replaces proxy authentication information in the request accordingly. |
{#authenticator-1}
Authenticator
Authenticator()
Creates an empty authenticator.
{#authenticator-2}
Authenticator
Authenticator(const std::string & username, const std::string & password)
Creates an authenticator with the given username and password.
{#authenticator-3}
~Authenticator
~Authenticator()
Destroys the authenticator.
{#fromuserinfo}
fromUserInfo
void fromUserInfo(std::string_view userInfo)
Parses username:password std::string and sets username and password of the credentials object. Throws SyntaxException on invalid user information.
{#fromuri}
fromURI
void fromURI(const http::URL & uri)
Extracts username and password from the given URI and sets username and password of the credentials object. Does nothing if URI has no user info part.
{#setusername}
setUsername
void setUsername(const std::string & username)
Sets the username.
{#username}
username
const
const std::string & username() const
Returns the username.
{#setpassword}
setPassword
void setPassword(const std::string & password)
Sets the password.
{#password}
password
const
const std::string & password() const
Returns the password.
{#authenticate}
authenticate
void authenticate(http::Request & request, const http::Response & response)
Inspects WWW-Authenticate header of the response, initializes the internal state (in case of digest authentication) and adds required information to the given http::Request.
{#updateauthinfo}
updateAuthInfo
void updateAuthInfo(http::Request & request)
Updates internal state (in case of digest authentication) and replaces authentication information in the request accordingly.
{#proxyauthenticate}
proxyAuthenticate
void proxyAuthenticate(http::Request & request, const http::Response & response)
Inspects Proxy-Authenticate header of the response, initializes the internal state (in case of digest authentication) and adds required information to the given http::Request.
{#updateproxyauthinfo}
updateProxyAuthInfo
void updateProxyAuthInfo(http::Request & request)
Updates internal state (in case of digest authentication) and replaces proxy authentication information in the request accordingly.
Private Attributes
| Return | Name | Description |
|---|---|---|
std::string | _username | |
std::string | _password |
{#_username}
_username
std::string _username
{#_password}
_password
std::string _password
Private Methods
| Return | Name | Description |
|---|---|---|
Authenticator | Deleted constructor. |
{#authenticator-4}
Authenticator
Authenticator(const Authenticator &) = delete
Deleted constructor.
{#basicauthenticator}
BasicAuthenticator
#include <icy/http/authenticator.h>
Encodes and decodes HTTP Basic authentication credentials.
Public Methods
| Return | Name | Description |
|---|---|---|
BasicAuthenticator | Creates an empty basic authenticator. | |
BasicAuthenticator | Creates a basic authenticator with the given username and password. | |
BasicAuthenticator explicit | Extracts basic authentication credentials from the given request. | |
BasicAuthenticator explicit | Parses a raw Basic authentication payload string. The value can be extracted from a request via [Request::getCredentials()](#getcredentials). | |
~BasicAuthenticator | Destroys the basic authenticator. | |
void | setUsername | Sets the username. |
const std::string & | username const | Returns the username. |
void | setPassword | Sets the password. |
const std::string & | password const | Returns the password. |
void | authenticate const | Adds authentication information to the given http::Request. |
void | proxyAuthenticate const | Adds proxy authentication information to the given http::Request. |
{#basicauthenticator-1}
BasicAuthenticator
BasicAuthenticator()
Creates an empty basic authenticator.
{#basicauthenticator-2}
BasicAuthenticator
BasicAuthenticator(const std::string & username, const std::string & password)
Creates a basic authenticator with the given username and password.
{#basicauthenticator-3}
BasicAuthenticator
explicit
explicit BasicAuthenticator(const http::Request & request)
Extracts basic authentication credentials from the given request.
Throws a NotAuthenticatedException if the request does not contain basic authentication information.
{#basicauthenticator-4}
BasicAuthenticator
explicit
explicit BasicAuthenticator(const std::string & authInfo)
Parses a raw Basic authentication payload string. The value can be extracted from a request via [Request::getCredentials()](#getcredentials).
{#basicauthenticator-5}
~BasicAuthenticator
~BasicAuthenticator()
Destroys the basic authenticator.
{#setusername-1}
setUsername
void setUsername(const std::string & username)
Sets the username.
{#username-1}
username
const
const std::string & username() const
Returns the username.
{#setpassword-1}
setPassword
void setPassword(const std::string & password)
Sets the password.
{#password-1}
password
const
const std::string & password() const
Returns the password.
{#authenticate-1}
authenticate
const
void authenticate(http::Request & request) const
Adds authentication information to the given http::Request.
{#proxyauthenticate-1}
proxyAuthenticate
const
void proxyAuthenticate(http::Request & request) const
Adds proxy authentication information to the given http::Request.
Protected Methods
| Return | Name | Description |
|---|---|---|
void | parseAuthInfo | Extracts username and password from Basic authentication info by base64-decoding authInfo and splitting the resulting std::string at the ':' delimiter. |
{#parseauthinfo}
parseAuthInfo
void parseAuthInfo(std::string_view authInfo)
Extracts username and password from Basic authentication info by base64-decoding authInfo and splitting the resulting std::string at the ':' delimiter.
Private Attributes
| Return | Name | Description |
|---|---|---|
std::string | _username | |
std::string | _password |
{#_username-1}
_username
std::string _username
{#_password-1}
_password
std::string _password
Private Methods
| Return | Name | Description |
|---|---|---|
BasicAuthenticator | Deleted constructor. |
{#basicauthenticator-6}
BasicAuthenticator
BasicAuthenticator(const BasicAuthenticator &) = delete
Deleted constructor.
{#chunkedadapter}
ChunkedAdapter
#include <icy/http/packetizers.h>
Inherits:
PacketProcessor
HTTP chunked transfer encoding adapter for streaming responses.
Public Attributes
| Return | Name | Description |
|---|---|---|
Connection::Ptr | connection | HTTP connection to send the initial response header through. |
std::string | contentType | Content-Type value for the chunked response. |
std::string | frameSeparator | Optional separator written before each chunk payload. |
bool | initial | True until the first chunk is processed and the header emitted. |
bool | nocopy | If true, header/data/footer are emitted as separate packets. |
PacketSignal | emitter |
{#connection}
connection
Connection::Ptr connection
HTTP connection to send the initial response header through.
{#contenttype}
contentType
std::string contentType
Content-Type value for the chunked response.
{#frameseparator}
frameSeparator
std::string frameSeparator
Optional separator written before each chunk payload.
{#initial}
initial
bool initial
True until the first chunk is processed and the header emitted.
{#nocopy}
nocopy
bool nocopy
If true, header/data/footer are emitted as separate packets.
{#emitter-5}
emitter
PacketSignal emitter
Public Methods
| Return | Name | Description |
|---|---|---|
ChunkedAdapter inline | Creates a ChunkedAdapter that sends its initial response header through the given connection. The content type is read from the connection's outgoing header. | |
ChunkedAdapter inline | Creates a ChunkedAdapter that emits its own raw HTTP/1.1 200 response header. Use this when no Connection object is available. | |
void | emitHeader virtual inline | Emits the initial HTTP/1.1 200 OK response headers with chunked transfer encoding. If a connection is set, headers are written through it; otherwise a raw response string is emitted via the packet signal. |
void | process virtual inline | Encodes an incoming packet as a chunked transfer encoding chunk and emits it. Emits the HTTP response headers on the first call. |
{#chunkedadapter-1}
ChunkedAdapter
inline
inline ChunkedAdapter(Connection::Ptr connection, const std::string & frameSeparator, bool nocopy)
Creates a ChunkedAdapter that sends its initial response header through the given connection. The content type is read from the connection's outgoing header.
Parameters
-
connectionHTTP connection to use. May be nullptr to emit a raw response instead. -
frameSeparatorOptional data prepended to each chunk payload. -
nocopyIf true, header and payload are emitted as separate packets (avoids copies).
{#chunkedadapter-2}
ChunkedAdapter
inline
inline ChunkedAdapter(const std::string & contentType, const std::string & frameSeparator, bool nocopy)
Creates a ChunkedAdapter that emits its own raw HTTP/1.1 200 response header. Use this when no Connection object is available.
Parameters
-
contentTypeContent-Type value for the response. -
frameSeparatorOptional data prepended to each chunk payload. -
nocopyIf true, header and payload are emitted as separate packets.
{#emitheader}
emitHeader
virtual inline
virtual inline void emitHeader()
Emits the initial HTTP/1.1 200 OK response headers with chunked transfer encoding. If a connection is set, headers are written through it; otherwise a raw response string is emitted via the packet signal.
{#process-5}
process
virtual inline
virtual inline void process(IPacket & packet)
Encodes an incoming packet as a chunked transfer encoding chunk and emits it. Emits the HTTP response headers on the first call.
Parameters
packetPacket containing the raw payload data.
Exceptions
std::invalid_argumentif the packet does not carry data.
{#client}
Client
#include <icy/http/client.h>
HTTP client for creating and managing outgoing connections.
Public Attributes
| Return | Name | Description |
|---|---|---|
NullSignal | Shutdown |
{#shutdown-6}
Shutdown
NullSignal Shutdown
Public Methods
| Return | Name | Description |
|---|---|---|
Client | ||
void | stop | Stop the Client and close all connections. |
ClientConnection::Ptr | createConnectionT inline | Creates and registers a typed client connection for the given URL. The connection type is inferred from the URL scheme (http, https, ws, wss). |
ClientConnection::Ptr | createConnection inline | Creates and registers a ClientConnection for the given URL. The socket type is chosen based on the URL scheme (http/https/ws/wss). |
void | addConnection virtual | Registers a connection with this client so it is tracked and cleaned up on stop(). |
void | removeConnection virtual | Removes a previously registered connection from the client. |
{#client-1}
Client
Client()
{#stop-7}
stop
void stop()
Stop the Client and close all connections.
{#createconnectiont-1}
createConnectionT
inline
template<class ConnectionT> inline ClientConnection::Ptr createConnectionT(const URL & url, uv::Loop * loop)
Creates and registers a typed client connection for the given URL. The connection type is inferred from the URL scheme (http, https, ws, wss).
Parameters
ConnectionTConcrete connection type derived from ClientConnection.
Parameters
-
urlTarget URL. The scheme determines the socket and adapter type. -
loopEvent loop to use. Defaults to the default libuv loop.
Returns
Shared pointer to the created connection.
{#createconnection-1}
createConnection
inline
inline ClientConnection::Ptr createConnection(const URL & url, uv::Loop * loop)
Creates and registers a ClientConnection for the given URL. The socket type is chosen based on the URL scheme (http/https/ws/wss).
Parameters
-
urlTarget URL. -
loopEvent loop to use. Defaults to the default libuv loop.
Returns
Shared pointer to the created connection.
{#addconnection}
addConnection
virtual
virtual void addConnection(ClientConnection::Ptr conn)
Registers a connection with this client so it is tracked and cleaned up on stop().
Parameters
connThe connection to add.
{#removeconnection}
removeConnection
virtual
virtual void removeConnection(ClientConnection * conn)
Removes a previously registered connection from the client.
Parameters
connRaw pointer to the connection to remove.
Exceptions
std::logic_errorif the connection is not tracked by this client.
Public Static Methods
| Return | Name | Description |
|---|---|---|
Client & | instance static | Return the default HTTP Client singleton. |
void | destroy static | Destroys the default HTTP Client singleton. |
{#instance-3}
instance
static
static Client & instance()
Return the default HTTP Client singleton.
{#destroy-1}
destroy
static
static void destroy()
Destroys the default HTTP Client singleton.
Protected Attributes
| Return | Name | Description |
|---|---|---|
ClientConnectionPtrVec | _connections |
{#_connections}
_connections
ClientConnectionPtrVec _connections
Protected Methods
| Return | Name | Description |
|---|---|---|
void | onConnectionClose |
{#onconnectionclose}
onConnectionClose
void onConnectionClose(Connection & conn)
{#clientconnection}
ClientConnection
#include <icy/http/client.h>
Inherits:
Connection
HTTP client connection for managing request/response lifecycle.
Public Attributes
| Return | Name | Description |
|---|---|---|
void * | opaque | Optional unmanaged client data pointer. Not used by the connection internally. |
NullSignal | Connect | Status signals. |
Signal< void(Response &)> | Headers | Signals when the response HTTP header has been received. |
Signal< void(const MutableBuffer &)> | Payload | Signals when raw data is received. |
Signal< void(const Response &)> | Complete | Signals when the HTTP transaction is complete. |
Signal< void(const icy::Error &)> | Error | Signals when the underlying transport reports an error. |
Signal< void(Connection &)> | Close | Signals when the connection is closed. |
ProgressSignal | IncomingProgress | Signals download progress (0-100%) |
{#opaque-1}
opaque
void * opaque
Optional unmanaged client data pointer. Not used by the connection internally.
{#connect-11}
Connect
NullSignal Connect
Status signals.
Signals when the client socket is connected and data can flow
{#headers}
Headers
Signal< void(Response &)> Headers
Signals when the response HTTP header has been received.
{#payload}
Payload
Signal< void(const MutableBuffer &)> Payload
Signals when raw data is received.
{#complete}
Complete
Signal< void(const Response &)> Complete
Signals when the HTTP transaction is complete.
{#error-9}
Error
Signal< void(const icy::Error &)> Error
Signals when the underlying transport reports an error.
{#close-19}
Close
Signal< void(Connection &)> Close
Signals when the connection is closed.
{#incomingprogress}
IncomingProgress
ProgressSignal IncomingProgress
Signals download progress (0-100%)
Public Methods
| Return | Name | Description |
|---|---|---|
ClientConnection | Creates a ClientConnection to the given URL, pre-populating the request URI and Host header. The response status is initialised to 502 Bad Gateway until a real response is received. | |
void | start virtual | Starts the internal HTTP request. |
void | start virtual | Starts the given HTTP request, replacing the internal request object. |
ssize_t | send virtual | Sends raw data to the peer, initiating a connection first if needed. Data is buffered internally until the connection is established. |
void | setReadStream virtual | Sets the output stream to which incoming response body data is written. The stream pointer is owned by the connection and freed with it. Must be called before start(). |
StreamT & | readStream inline | Returns a reference to the read stream cast to the specified type. |
{#clientconnection-1}
ClientConnection
ClientConnection(const URL & url, const net::TCPSocket::Ptr & socket)
Creates a ClientConnection to the given URL, pre-populating the request URI and Host header. The response status is initialised to 502 Bad Gateway until a real response is received.
Parameters
-
urlTarget URL. Scheme, host, port and path are extracted automatically. -
socketTCP socket to use. Defaults to a plain TCPSocket; pass an SSLSocket for HTTPS.
{#start-8}
start
virtual
virtual void start()
Starts the internal HTTP request.
Calls connect() internally if the socket is not already connecting or connected. The actual request will be sent when the socket is connected.
Exceptions
std::runtime_errorif already connecting.
{#start-9}
start
virtual
virtual void start(http::Request & req)
Starts the given HTTP request, replacing the internal request object.
Calls connect() internally if the socket is not already connecting or connected. The actual request will be sent when the socket is connected.
Parameters
reqThe HTTP request to send. Replaces the internal request.
Exceptions
std::runtime_errorif already connecting.
{#send-10}
send
virtual
virtual ssize_t send(const char * data, size_t len, int flags)
Sends raw data to the peer, initiating a connection first if needed. Data is buffered internally until the connection is established.
Parameters
-
dataPointer to the data buffer. -
lenNumber of bytes to send. -
flagsSocket send flags (unused for HTTP).
Returns
Number of bytes sent or buffered.
{#setreadstream}
setReadStream
virtual
virtual void setReadStream(std::ostream * os)
Sets the output stream to which incoming response body data is written. The stream pointer is owned by the connection and freed with it. Must be called before start().
Parameters
osPointer to the output stream. Takes ownership.
Exceptions
std::runtime_errorif already connecting.
{#readstream}
readStream
inline
template<class StreamT> inline StreamT & readStream()
Returns a reference to the read stream cast to the specified type.
Parameters
StreamTThe concrete stream type to cast to.
Returns
Reference to the stream.
Exceptions
-
std::runtime_errorif no read stream has been set. -
std::bad_castif the stream is not of type StreamT.
Protected Attributes
| Return | Name | Description |
|---|---|---|
URL | _url | |
bool | _connect | |
bool | _active | |
bool | _complete | |
std::vector< PendingWrite > | _outgoingBuffer | |
std::unique_ptr< std::ostream > | _readStream |
{#_url}
_url
URL _url
{#_connect}
_connect
bool _connect
{#_active}
_active
bool _active
{#_complete}
_complete
bool _complete
{#_outgoingbuffer}
_outgoingBuffer
std::vector< PendingWrite > _outgoingBuffer
{#_readstream}
_readStream
std::unique_ptr< std::ostream > _readStream
Protected Methods
| Return | Name | Description |
|---|---|---|
void | connect virtual | Connects to the server endpoint. All sent data is buffered until the connection is made. |
http::Message * | incomingHeader virtual | Returns the incoming HTTP message header (request or response depending on role). |
http::Message * | outgoingHeader virtual | Returns the outgoing HTTP message header (request or response depending on role). |
bool | onSocketConnect virtual | net::SocketAdapter interface |
{#connect-12}
connect
virtual
virtual void connect()
Connects to the server endpoint. All sent data is buffered until the connection is made.
{#incomingheader}
incomingHeader
virtual
virtual http::Message * incomingHeader()
Returns the incoming HTTP message header (request or response depending on role).
{#outgoingheader}
outgoingHeader
virtual
virtual http::Message * outgoingHeader()
Returns the outgoing HTTP message header (request or response depending on role).
{#onsocketconnect-2}
onSocketConnect
virtual
virtual bool onSocketConnect(net::Socket & socket)
net::SocketAdapter interface
Public Types
| Name | Description |
|---|---|
Ptr |
{#ptr-11}
Ptr
std::shared_ptr< ClientConnection > Ptr()
Private Methods
| Return | Name | Description |
|---|---|---|
void | onHeaders virtual | Connection interface. |
void | onPayload virtual | Called for each chunk of incoming response body data. |
void | onComplete virtual | Called when the full HTTP response has been received. |
void | onClose virtual | Called when the connection is closed. |
bool | onSocketError virtual | Called when the underlying transport encounters an error. |
{#onheaders}
onHeaders
virtual
virtual void onHeaders()
Connection interface.
Called when the response headers have been parsed.
{#onpayload}
onPayload
virtual
virtual void onPayload(const MutableBuffer & buffer)
Called for each chunk of incoming response body data.
{#oncomplete}
onComplete
virtual
virtual void onComplete()
Called when the full HTTP response has been received.
{#onclose-3}
onClose
virtual
virtual void onClose()
Called when the connection is closed.
{#onsocketerror-2}
onSocketError
virtual
virtual bool onSocketError(net::Socket & socket, const icy::Error & error)
Called when the underlying transport encounters an error.
{#pendingwrite}
PendingWrite
#include <icy/http/client.h>
Public Attributes
| Return | Name | Description |
|---|---|---|
Buffer | data | |
int | flags |
{#data-1}
data
Buffer data
{#flags}
flags
int flags = 0
{#connection-1}
Connection
#include <icy/http/connection.h>
Inherits:
SocketAdapterSubclassed by:ClientConnection,ServerConnection
Base HTTP connection managing socket I/O and message lifecycle
Public Methods
| Return | Name | Description |
|---|---|---|
Connection | Creates a Connection using the given TCP socket. | |
void | onHeaders | Called when the incoming HTTP headers have been fully parsed. |
void | onPayload | Called for each chunk of incoming body data after headers are complete. |
void | onComplete | Called when the incoming HTTP message is fully received. |
void | onClose | Called when the connection is closed. |
ssize_t | send virtual | Send raw data to the peer. |
ssize_t | sendOwned virtual | Send an owned payload buffer to the peer. |
ssize_t | sendHeader virtual | Send the outdoing HTTP header. |
void | close virtual | Close the connection and schedule the object for deferred deletion. |
void | markActive virtual inline | Marks the connection as active. Server connections override this to refresh the idle timer. |
void | beginStreaming virtual inline | Explicitly enter long-lived streaming mode. Base connections ignore this; server connections use it to disable keep-alive idle reaping while a response stream is active. |
void | endStreaming virtual inline | Exit long-lived streaming mode. |
bool | closed const | Return true if the connection is closed. |
icy::Error | error const | Return the error object if any. |
bool | headerAutoSendEnabled const | Return true if headers should be automatically sent. |
void | setHeaderAutoSendEnabled | Enable or disable automatic header emission for the next outgoing send path. |
void | replaceAdapter virtual | Assign the new ConnectionAdapter and setup the chain. The flow is: Connection <-> ConnectionAdapter <-> Socket. Takes ownership of the adapter (deferred deletion via uv loop). |
void | replaceAdapter virtual | Overload for nullptr (used in destructor to clear adapter). |
bool | secure const | Return true if the connection uses TLS/SSL. |
net::TCPSocket::Ptr & | socket | Return the underlying socket pointer. |
net::SocketAdapter * | adapter const | Return the underlying adapter pointer. |
Request & | request | The HTTP request headers. |
Response & | response | The HTTP response headers. |
http::Message * | incomingHeader | Returns the incoming HTTP message header (request or response depending on role). |
http::Message * | outgoingHeader | Returns the outgoing HTTP message header (request or response depending on role). |
{#connection-2}
Connection
Connection(const net::TCPSocket::Ptr & socket)
Creates a Connection using the given TCP socket.
Parameters
socketThe TCP socket to use for I/O. Defaults to a new TCPSocket.
{#onheaders-1}
onHeaders
void onHeaders()
Called when the incoming HTTP headers have been fully parsed.
{#onpayload-1}
onPayload
void onPayload(const MutableBuffer & buffer)
Called for each chunk of incoming body data after headers are complete.
Parameters
bufferBuffer containing the received data chunk.
{#oncomplete-1}
onComplete
void onComplete()
Called when the incoming HTTP message is fully received.
{#onclose-4}
onClose
void onClose()
Called when the connection is closed.
{#send-11}
send
virtual
virtual ssize_t send(const char * data, size_t len, int flags)
Send raw data to the peer.
This is the zero-copy fast path. The caller retains ownership of the payload until the underlying async write completes.
{#sendowned-10}
sendOwned
virtual
virtual ssize_t sendOwned(Buffer && buffer, int flags)
Send an owned payload buffer to the peer.
Use this when the payload does not naturally outlive the current scope.
{#sendheader}
sendHeader
virtual
virtual ssize_t sendHeader()
Send the outdoing HTTP header.
{#close-20}
close
virtual
virtual void close()
Close the connection and schedule the object for deferred deletion.
{#markactive}
markActive
virtual inline
virtual inline void markActive()
Marks the connection as active. Server connections override this to refresh the idle timer.
{#beginstreaming}
beginStreaming
virtual inline
virtual inline void beginStreaming()
Explicitly enter long-lived streaming mode. Base connections ignore this; server connections use it to disable keep-alive idle reaping while a response stream is active.
{#endstreaming}
endStreaming
virtual inline
virtual inline void endStreaming()
Exit long-lived streaming mode.
{#closed-4}
closed
const
bool closed() const
Return true if the connection is closed.
{#error-10}
error
const
icy::Error error() const
Return the error object if any.
{#headerautosendenabled}
headerAutoSendEnabled
const
bool headerAutoSendEnabled() const
Return true if headers should be automatically sent.
{#setheaderautosendenabled}
setHeaderAutoSendEnabled
void setHeaderAutoSendEnabled(bool enabled)
Enable or disable automatic header emission for the next outgoing send path.
{#replaceadapter}
replaceAdapter
virtual
virtual void replaceAdapter(std::unique_ptr< net::SocketAdapter > adapter)
Assign the new ConnectionAdapter and setup the chain. The flow is: Connection <-> ConnectionAdapter <-> Socket. Takes ownership of the adapter (deferred deletion via uv loop).
{#replaceadapter-1}
replaceAdapter
virtual
virtual void replaceAdapter(std::nullptr_t)
Overload for nullptr (used in destructor to clear adapter).
{#secure}
secure
const
bool secure() const
Return true if the connection uses TLS/SSL.
{#socket-5}
socket
net::TCPSocket::Ptr & socket()
Return the underlying socket pointer.
{#adapter}
adapter
const
net::SocketAdapter * adapter() const
Return the underlying adapter pointer.
{#request-3}
request
Request & request()
The HTTP request headers.
{#response}
response
Response & response()
The HTTP response headers.
{#incomingheader-1}
incomingHeader
http::Message * incomingHeader()
Returns the incoming HTTP message header (request or response depending on role).
{#outgoingheader-1}
outgoingHeader
http::Message * outgoingHeader()
Returns the outgoing HTTP message header (request or response depending on role).
Protected Attributes
| Return | Name | Description |
|---|---|---|
net::TCPSocket::Ptr | _socket | |
net::SocketAdapter * | _adapter | |
Request | _request | |
Response | _response | |
icy::Error | _error | |
bool | _closed | |
bool | _shouldSendHeader |
{#_socket-1}
_socket
net::TCPSocket::Ptr _socket
{#_adapter}
_adapter
net::SocketAdapter * _adapter
{#_request}
_request
Request _request
{#_response}
_response
Response _response
{#_error-2}
_error
icy::Error _error
{#_closed}
_closed
bool _closed
{#_shouldsendheader}
_shouldSendHeader
bool _shouldSendHeader
Protected Methods
| Return | Name | Description |
|---|---|---|
void | setError virtual | Set the internal error. Note: Setting the error does not [close()](#close-20) the connection. |
bool | onSocketConnect virtual | net::SocketAdapter interface |
bool | onSocketRecv virtual | Called when data is received from the socket. Forwards the event to all registered receivers in priority order. |
bool | onSocketError virtual | Called when the socket encounters an error. Forwards the event to all registered receivers in priority order. |
bool | onSocketClose virtual | Called when the socket is closed. Forwards the event to all registered receivers in priority order. |
{#seterror-4}
setError
virtual
virtual void setError(const icy::Error & err)
Set the internal error. Note: Setting the error does not [close()](#close-20) the connection.
{#onsocketconnect-3}
onSocketConnect
virtual
virtual bool onSocketConnect(net::Socket & socket)
net::SocketAdapter interface
{#onsocketrecv-3}
onSocketRecv
virtual
virtual bool onSocketRecv(net::Socket & socket, const MutableBuffer & buffer, const net::Address & peerAddress)
Called when data is received from the socket. Forwards the event to all registered receivers in priority order.
Parameters
-
socketThe socket that received data. -
bufferThe received data buffer. -
peerAddressAddress of the sender.
Returns
true to stop propagation to subsequent receivers.
{#onsocketerror-3}
onSocketError
virtual
virtual bool onSocketError(net::Socket & socket, const icy::Error & error)
Called when the socket encounters an error. Forwards the event to all registered receivers in priority order.
Parameters
-
socketThe socket that encountered the error. -
errorError details.
Returns
true to stop propagation to subsequent receivers.
{#onsocketclose-2}
onSocketClose
virtual
virtual bool onSocketClose(net::Socket & socket)
Called when the socket is closed. Forwards the event to all registered receivers in priority order.
Parameters
socketThe socket that was closed.
Returns
true to stop propagation to subsequent receivers.
Public Types
| Name | Description |
|---|---|
Ptr |
{#ptr-12}
Ptr
std::shared_ptr< Connection > Ptr()
{#connectionadapter}
ConnectionAdapter
#include <icy/http/connection.h>
Inherits:
ParserObserver,SocketAdapter
Default HTTP socket adapter for reading and writing HTTP messages
Public Methods
| Return | Name | Description |
|---|---|---|
ConnectionAdapter | Creates a ConnectionAdapter for the given connection. | |
ssize_t | send virtual | Sends data to the peer, flushing the outgoing HTTP header first if needed. |
ssize_t | sendOwned virtual | Sends an owned payload buffer to the connected peer. |
void | removeReceiver | Remove the given receiver. |
Parser & | parser | Returns the HTTP parser instance. |
Connection * | connection | Returns the owning Connection pointer, or nullptr if detached. |
void | reset | Resets the adapter for reuse with a new socket and request. Clears the parser state and re-wires the sender without reallocating. Used by the connection pool to avoid destroying/recreating adapters. |
{#connectionadapter-1}
ConnectionAdapter
ConnectionAdapter(Connection * connection, llhttp_type_t type)
Creates a ConnectionAdapter for the given connection.
Parameters
-
connectionOwning HTTP connection. -
typeParser type: HTTP_REQUEST for server side, HTTP_RESPONSE for client side.
{#send-12}
send
virtual
virtual ssize_t send(const char * data, size_t len, int flags)
Sends data to the peer, flushing the outgoing HTTP header first if needed.
Parameters
-
dataPointer to the data buffer. -
lenNumber of bytes to send. -
flagsSend flags (unused for HTTP, used for WebSocket frame type).
Returns
Number of bytes sent, or -1 on error.
{#sendowned-11}
sendOwned
virtual
virtual ssize_t sendOwned(Buffer && buffer, int flags)
Sends an owned payload buffer to the connected peer.
The buffer is moved through the adapter chain and retained by the transport layer until async write completion.
{#removereceiver-2}
removeReceiver
void removeReceiver(SocketAdapter * adapter)
Remove the given receiver.
By default this function does nothing unless the given receiver matches the current receiver.
{#parser}
parser
Parser & parser()
Returns the HTTP parser instance.
{#connection-3}
connection
Connection * connection()
Returns the owning Connection pointer, or nullptr if detached.
{#reset-7}
reset
void reset(net::SocketAdapter * sender, http::Request * request)
Resets the adapter for reuse with a new socket and request. Clears the parser state and re-wires the sender without reallocating. Used by the connection pool to avoid destroying/recreating adapters.
Parameters
-
senderNew socket adapter to send data through. -
requestNew HTTP request object for the parser to populate.
Protected Attributes
| Return | Name | Description |
|---|---|---|
Connection * | _connection | |
Parser | _parser |
{#_connection}
_connection
Connection * _connection
{#_parser}
_parser
Parser _parser
Protected Methods
| Return | Name | Description |
|---|---|---|
bool | onSocketRecv virtual | SocketAdapter interface. |
void | onParserHeader virtual | HTTP Parser interface. |
void | onParserHeadersEnd virtual | Called when all HTTP headers have been parsed. |
void | onParserChunk virtual | Called for each chunk of body data received. |
void | onParserError virtual | Called when a parse error occurs. |
void | onParserEnd virtual | Called when the HTTP message is fully parsed. |
{#onsocketrecv-4}
onSocketRecv
virtual
virtual bool onSocketRecv(net::Socket & socket, const MutableBuffer & buffer, const net::Address & peerAddress)
SocketAdapter interface.
{#onparserheader}
onParserHeader
virtual
virtual void onParserHeader(const std::string & name, const std::string & value)
HTTP Parser interface.
{#onparserheadersend}
onParserHeadersEnd
virtual
virtual void onParserHeadersEnd(bool upgrade)
Called when all HTTP headers have been parsed.
Parameters
upgradeTrue if the connection should be upgraded (e.g. to WebSocket).
{#onparserchunk}
onParserChunk
virtual
virtual void onParserChunk(const char * data, size_t len)
Called for each chunk of body data received.
Parameters
-
dataPointer to the body data chunk. -
lenLength of the chunk in bytes.
{#onparsererror}
onParserError
virtual
virtual void onParserError(const icy::Error & err)
Called when a parse error occurs.
Parameters
errError details from llhttp.
{#onparserend}
onParserEnd
virtual
virtual void onParserEnd()
Called when the HTTP message is fully parsed.
{#connectionpool}
ConnectionPool
#include <icy/http/server.h>
LIFO connection pool for reusing ServerConnection objects. Avoids per-request heap allocation by resetting and reusing connections instead of destroying and recreating them.
Public Methods
| Return | Name | Description |
|---|---|---|
ServerConnection::Ptr | acquire inline | Takes a connection from the pool for reuse. |
bool | release inline | Returns a connection to the pool after use. |
void | setMaxSize inline | Sets the maximum number of connections the pool will hold. |
size_t | size const inline | Returns the current number of connections held in the pool. |
{#acquire}
acquire
inline
inline ServerConnection::Ptr acquire()
Takes a connection from the pool for reuse.
Returns
A pooled connection, or nullptr if the pool is empty.
{#release}
release
inline
inline bool release(ServerConnection::Ptr & conn)
Returns a connection to the pool after use.
Parameters
connThe connection to return.
Returns
true if accepted into the pool; false if the pool is full.
{#setmaxsize}
setMaxSize
inline
inline void setMaxSize(size_t n)
Sets the maximum number of connections the pool will hold.
Parameters
nMaximum pool capacity.
{#size}
size
const inline
inline size_t size() const
Returns the current number of connections held in the pool.
Private Attributes
| Return | Name | Description |
|---|---|---|
std::vector< ServerConnection::Ptr > | _pool | |
size_t | _maxSize |
{#_pool}
_pool
std::vector< ServerConnection::Ptr > _pool
{#_maxsize}
_maxSize
size_t _maxSize = 128
{#connectionstream}
ConnectionStream
#include <icy/http/connection.h>
Inherits:
SocketAdapter
Packet stream wrapper for an HTTP connection.
Public Attributes
| Return | Name | Description |
|---|---|---|
PacketStream | Outgoing | The Outgoing stream is responsible for packetizing raw application data into the agreed upon HTTP format and sending it to the peer. |
PacketStream | Incoming | The Incoming stream emits incoming HTTP packets for processing by the application. |
ProgressSignal | IncomingProgress | Fired on download progress. |
ProgressSignal | OutgoingProgress | Fired on upload progress. |
{#outgoing}
Outgoing
PacketStream Outgoing
The Outgoing stream is responsible for packetizing raw application data into the agreed upon HTTP format and sending it to the peer.
{#incoming}
Incoming
PacketStream Incoming
The Incoming stream emits incoming HTTP packets for processing by the application.
This is useful for example when writing incoming data to a file.
{#incomingprogress-1}
IncomingProgress
ProgressSignal IncomingProgress
Fired on download progress.
{#outgoingprogress}
OutgoingProgress
ProgressSignal OutgoingProgress
Fired on upload progress.
Public Methods
| Return | Name | Description |
|---|---|---|
ConnectionStream | Creates a ConnectionStream wrapping the given HTTP connection. Wires the Outgoing stream emitter to the connection adapter and registers this stream to receive incoming data from the adapter. | |
ssize_t | send virtual | Send data via the Outgoing stream. |
Connection::Ptr | connection | Return a reference to the underlying connection. |
{#connectionstream-1}
ConnectionStream
ConnectionStream(Connection::Ptr connection)
Creates a ConnectionStream wrapping the given HTTP connection. Wires the Outgoing stream emitter to the connection adapter and registers this stream to receive incoming data from the adapter.
Parameters
connectionThe HTTP connection to wrap.
{#send-13}
send
virtual
virtual ssize_t send(const char * data, size_t len, int flags)
Send data via the Outgoing stream.
{#connection-4}
connection
Connection::Ptr connection()
Return a reference to the underlying connection.
Protected Attributes
| Return | Name | Description |
|---|---|---|
Connection::Ptr | _connection |
{#_connection-1}
_connection
Connection::Ptr _connection
Protected Methods
| Return | Name | Description |
|---|---|---|
bool | onSocketRecv virtual | Called when data is received from the socket. Forwards the event to all registered receivers in priority order. |
{#onsocketrecv-5}
onSocketRecv
virtual
virtual bool onSocketRecv(net::Socket & socket, const MutableBuffer & buffer, const net::Address & peerAddress)
Called when data is received from the socket. Forwards the event to all registered receivers in priority order.
Parameters
-
socketThe socket that received data. -
bufferThe received data buffer. -
peerAddressAddress of the sender.
Returns
true to stop propagation to subsequent receivers.
{#cookie}
Cookie
#include <icy/http/cookie.h>
HTTP cookie value plus its response/header attributes.
A cookie is a small amount of information sent by a Web server to a Web browser, saved by the browser, and later sent back to the server. A cookie's value can uniquely identify a client, so cookies are commonly used for session management.
A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.
This class supports both the Version 0 (by Netscape) and Version 1 (by RFC 2109) cookie specifications. By default, cookies are created using Version 0 to ensure the best interoperability.
Public Methods
| Return | Name | Description |
|---|---|---|
Cookie | Creates an empty Cookie. | |
Cookie explicit | Creates a cookie with the given name. The cookie never expires. | |
Cookie explicit | Creates a cookie from the given NVCollection. | |
Cookie | Creates a cookie with the given name and value. The cookie never expires. | |
Cookie | Creates the Cookie by copying another one. | |
~Cookie | Destroys the Cookie. | |
Cookie & | operator= | Assigns a cookie. |
void | setVersion | Sets the version of the cookie. |
int | getVersion const inline | Returns the version of the cookie, which is either 0 or 1. |
void | setName | Sets the name of the cookie. |
const std::string & | getName const inline | Returns the name of the cookie. |
void | setValue | Sets the value of the cookie. |
const std::string & | getValue const inline | Returns the value of the cookie. |
void | setComment | Sets the comment for the cookie. |
const std::string & | getComment const inline | Returns the comment for the cookie. |
void | setDomain | Sets the domain for the cookie. |
const std::string & | getDomain const inline | Returns the domain for the cookie. |
void | setPath | Sets the path for the cookie. |
const std::string & | getPath const inline | Returns the path for the cookie. |
void | setSecure | Sets the value of the secure flag for the cookie. |
bool | getSecure const inline | Returns the value of the secure flag for the cookie. |
void | setMaxAge | Sets the maximum age in seconds for the cookie. |
int | getMaxAge const inline | Returns the maximum age in seconds for the cookie. |
void | setHttpOnly | Sets the HttpOnly flag for the cookie. |
bool | getHttpOnly const inline | Returns true if the cookie's HttpOnly flag is set. |
std::string | toString const | Returns a std::string representation of the cookie, suitable for use in a Set-Cookie header. |
{#cookie-1}
Cookie
Cookie()
Creates an empty Cookie.
{#cookie-2}
Cookie
explicit
explicit Cookie(const std::string & name)
Creates a cookie with the given name. The cookie never expires.
{#cookie-3}
Cookie
explicit
explicit Cookie(const NVCollection & nvc)
Creates a cookie from the given NVCollection.
{#cookie-4}
Cookie
Cookie(const std::string & name, const std::string & value)
Creates a cookie with the given name and value. The cookie never expires.
Note: If value contains whitespace or non-alphanumeric characters, the value should be escaped by calling escape() before passing it to the constructor.
{#cookie-5}
Cookie
Cookie(const Cookie & cookie)
Creates the Cookie by copying another one.
{#cookie-6}
~Cookie
~Cookie()
Destroys the Cookie.
{#operator-14}
operator=
Cookie & operator=(const Cookie & cookie)
Assigns a cookie.
{#setversion}
setVersion
void setVersion(int version)
Sets the version of the cookie.
Version must be either 0 (denoting a Netscape cookie) or 1 (denoting a RFC 2109 cookie).
{#getversion}
getVersion
const inline
inline int getVersion() const
Returns the version of the cookie, which is either 0 or 1.
{#setname}
setName
void setName(const std::string & name)
Sets the name of the cookie.
{#getname}
getName
const inline
inline const std::string & getName() const
Returns the name of the cookie.
{#setvalue}
setValue
void setValue(const std::string & value)
Sets the value of the cookie.
According to the cookie specification, the size of the value should not exceed 4 Kbytes.
Note: If value contains whitespace or non-alphanumeric characters, the value should be escaped by calling escape() prior to passing it to setName().
{#getvalue}
getValue
const inline
inline const std::string & getValue() const
Returns the value of the cookie.
{#setcomment}
setComment
void setComment(const std::string & comment)
Sets the comment for the cookie.
Comments are only supported for version 1 cookies.
{#getcomment}
getComment
const inline
inline const std::string & getComment() const
Returns the comment for the cookie.
{#setdomain}
setDomain
void setDomain(const std::string & domain)
Sets the domain for the cookie.
{#getdomain}
getDomain
const inline
inline const std::string & getDomain() const
Returns the domain for the cookie.
{#setpath}
setPath
void setPath(const std::string & path)
Sets the path for the cookie.
{#getpath}
getPath
const inline
inline const std::string & getPath() const
Returns the path for the cookie.
{#setsecure}
setSecure
void setSecure(bool secure)
Sets the value of the secure flag for the cookie.
{#getsecure}
getSecure
const inline
inline bool getSecure() const
Returns the value of the secure flag for the cookie.
{#setmaxage}
setMaxAge
void setMaxAge(int maxAge)
Sets the maximum age in seconds for the cookie.
A value of -1 causes the cookie to never expire on the client.
A value of 0 deletes the cookie on the client.
{#getmaxage}
getMaxAge
const inline
inline int getMaxAge() const
Returns the maximum age in seconds for the cookie.
{#sethttponly}
setHttpOnly
void setHttpOnly(bool flag)
Sets the HttpOnly flag for the cookie.
{#gethttponly}
getHttpOnly
const inline
inline bool getHttpOnly() const
Returns true if the cookie's HttpOnly flag is set.
{#tostring-5}
toString
const
std::string toString() const
Returns a std::string representation of the cookie, suitable for use in a Set-Cookie header.
Public Static Methods
| Return | Name | Description |
|---|---|---|
std::string | escape static | Escapes the given std::string by replacing all non-alphanumeric characters with escape sequences in the form xx, where xx is the hexadecimal character code. |
std::string | unescape static | Unescapes the given std::string by replacing all escape sequences in the form xx with the respective characters. |
{#escape}
escape
static
static std::string escape(std::string_view str)
Escapes the given std::string by replacing all non-alphanumeric characters with escape sequences in the form xx, where xx is the hexadecimal character code.
{#unescape}
unescape
static
static std::string unescape(std::string_view str)
Unescapes the given std::string by replacing all escape sequences in the form xx with the respective characters.
Private Attributes
| Return | Name | Description |
|---|---|---|
int | _version | |
std::string | _name | |
std::string | _value | |
std::string | _comment | |
std::string | _domain | |
std::string | _path | |
bool | _secure | |
int | _maxAge | |
bool | _httpOnly |
{#_version}
_version
int _version
{#_name}
_name
std::string _name
{#_value}
_value
std::string _value
{#_comment}
_comment
std::string _comment
{#_domain}
_domain
std::string _domain
{#_path}
_path
std::string _path
{#_secure}
_secure
bool _secure
{#_maxage}
_maxAge
int _maxAge
{#_httponly}
_httpOnly
bool _httpOnly
{#filepart}
FilePart
#include <icy/http/form.h>
Inherits:
FormPart
Form part backed by a file on disk.
Public Methods
| Return | Name | Description |
|---|---|---|
FilePart | Creates the FilePart for the given path. | |
FilePart | Creates the FilePart for the given path and MIME type. | |
FilePart | Creates the FilePart for the given path and MIME type. The given filename is used as part filename (see filename()) only. | |
~FilePart virtual | Destroys the FilePart. | |
void | open virtual | Opens the file for reading. |
void | reset virtual | Resets the file stream to the beginning and clears initial-write state. |
bool | writeChunk virtual | Writes the next chunk of the file to the FormWriter. |
void | write virtual | Writes the entire file content to the FormWriter. |
void | write virtual | Writes the entire file content to an output stream (used for content-length calculation). |
const std::string & | filename const | Returns the filename component of the file path (not the full path). |
std::ifstream & | stream | Returns a reference to the underlying file input stream. |
uint64_t | length virtual const | Returns the total file size in bytes. |
{#filepart-1}
FilePart
FilePart(const std::string & path)
Creates the FilePart for the given path.
The MIME type is set to application/octet-stream.
Throws an FileException if the file cannot be opened.
{#filepart-2}
FilePart
FilePart(const std::string & path, const std::string & contentType)
Creates the FilePart for the given path and MIME type.
Throws an FileException if the file cannot be opened.
{#filepart-3}
FilePart
FilePart(const std::string & path, const std::string & filename, const std::string & contentType)
Creates the FilePart for the given path and MIME type. The given filename is used as part filename (see filename()) only.
Throws an FileException if the file cannot be opened.
{#filepart-4}
~FilePart
virtual
virtual ~FilePart()
Destroys the FilePart.
{#open-4}
open
virtual
virtual void open()
Opens the file for reading.
Exceptions
std::runtime_errorif the file cannot be opened.
{#reset-8}
reset
virtual
virtual void reset()
Resets the file stream to the beginning and clears initial-write state.
{#writechunk}
writeChunk
virtual
virtual bool writeChunk(FormWriter & writer)
Writes the next chunk of the file to the FormWriter.
Parameters
writerThe FormWriter to send the chunk through.
Returns
true if more data remains; false when the file is fully sent.
{#write-2}
write
virtual
virtual void write(FormWriter & writer)
Writes the entire file content to the FormWriter.
Parameters
writerThe FormWriter to send data through.
{#write-3}
write
virtual
virtual void write(std::ostream & ostr)
Writes the entire file content to an output stream (used for content-length calculation).
Parameters
ostrOutput stream to write to.
{#filename-1}
filename
const
const std::string & filename() const
Returns the filename component of the file path (not the full path).
{#stream-3}
stream
std::ifstream & stream()
Returns a reference to the underlying file input stream.
{#length-1}
length
virtual const
virtual uint64_t length() const
Returns the total file size in bytes.
Protected Attributes
| Return | Name | Description |
|---|---|---|
std::string | _path | |
std::string | _filename | |
std::ifstream | _istr | |
uint64_t | _fileSize |
{#_path-1}
_path
std::string _path
{#_filename-1}
_filename
std::string _filename
{#_istr}
_istr
std::ifstream _istr
{#_filesize}
_fileSize
uint64_t _fileSize
{#formpart}
FormPart
#include <icy/http/form.h>
Subclassed by:
FilePart,StringPart
An implementation of FormPart.
Public Methods
| Return | Name | Description |
|---|---|---|
FormPart | Creates the FormPart with the given MIME content type. | |
~FormPart virtual | Destroys the FormPart. | |
void | reset virtual | Resets the internal state and write position to the beginning. Called by FormWriter when retrying or recalculating content length. |
bool | writeChunk | Writes the next chunk of data to the FormWriter. |
void | write | Writes the entire part data to the FormWriter in one call. |
void | write | Writes the entire part data to an output stream (used for content-length calculation). |
NVCollection & | headers | Returns the extra MIME headers for this part (e.g. Content-Disposition). |
bool | initialWrite virtual const | Returns true if this is the first write call since construction or reset(). |
const std::string & | contentType const | Returns the MIME content type for this part. |
uint64_t | length const | Returns the total byte length of the part data. |
{#formpart-1}
FormPart
FormPart(const std::string & contentType)
Creates the FormPart with the given MIME content type.
Parameters
contentTypeMIME type for this part (default: "application/octet-stream").
{#formpart-2}
~FormPart
virtual
virtual ~FormPart()
Destroys the FormPart.
{#reset-9}
reset
virtual
virtual void reset()
Resets the internal state and write position to the beginning. Called by FormWriter when retrying or recalculating content length.
{#writechunk-1}
writeChunk
bool writeChunk(FormWriter & writer)
Writes the next chunk of data to the FormWriter.
Parameters
writerThe FormWriter to send the chunk through.
Returns
true if more data remains to be written; false when complete.
{#write-4}
write
void write(FormWriter & writer)
Writes the entire part data to the FormWriter in one call.
Parameters
writerThe FormWriter to send data through.
{#write-5}
write
void write(std::ostream & ostr)
Writes the entire part data to an output stream (used for content-length calculation).
Parameters
ostrOutput stream to write to.
{#headers-1}
headers
NVCollection & headers()
Returns the extra MIME headers for this part (e.g. Content-Disposition).
{#initialwrite}
initialWrite
virtual const
virtual bool initialWrite() const
Returns true if this is the first write call since construction or reset().
{#contenttype-1}
contentType
const
const std::string & contentType() const
Returns the MIME content type for this part.
{#length-2}
length
const
uint64_t length() const
Returns the total byte length of the part data.
Protected Attributes
| Return | Name | Description |
|---|---|---|
std::string | _contentType | |
uint64_t | _length | |
NVCollection | _headers | |
bool | _initialWrite |
{#_contenttype}
_contentType
std::string _contentType
{#_length}
_length
uint64_t _length
{#_headers}
_headers
NVCollection _headers
{#_initialwrite}
_initialWrite
bool _initialWrite
{#formwriter}
FormWriter
#include <icy/http/form.h>
Inherits:
NVCollection,PacketStreamAdapter,Startable
FormWriter is an HTTP client connection adapter for writing HTML forms.
This class runs in its own thread so as not to block the event loop while uploading big files. Class members are not synchronized hence they should not be accessed while the form is sending, not that there would be any reason to do so.
Public Attributes
| Return | Name | Description |
|---|---|---|
PacketSignal | emitter | The outgoing packet emitter. |
{#emitter-6}
emitter
PacketSignal emitter
The outgoing packet emitter.
Public Methods
| Return | Name | Description |
|---|---|---|
~FormWriter virtual | Destroys the FormWriter. | |
void | addPart | Adds a part or file attachment to the multipart form. |
void | start virtual | Starts the sending thread. |
void | stop virtual | Stops the sending thread. |
bool | complete const | Returns true if the request is complete. |
bool | cancelled const | Returns true if the request is cancelled. |
void | prepareSubmit | Prepares the outgoing HTTP request object for submitting the form. |
uint64_t | calculateMultipartContentLength | Processes the entire form body and computes its total byte length. Only meaningful for multipart/form-data when not using chunked encoding. |
void | writeUrl | Writes the complete "application/x-www-form-urlencoded" encoded body to ostr. All key-value pairs from the NVCollection base are percent-encoded and joined with '&'. |
void | writeMultipartChunk | Writes the next pending multipart chunk to the connection. Non-blocking; intended to be called repeatedly from the event loop until all parts have been sent. |
void | writeAsync | Writes the next message chunk from the background runner thread. Called by the Runner; do not call directly. |
void | setEncoding | Sets the MIME encoding used for submitting the form. Must be set before prepareSubmit() is called. |
const std::string & | encoding const | Returns the encoding used for posting the form. |
void | setBoundary | Sets the MIME boundary string used to delimit multipart form parts. If not set, a random boundary is generated by prepareSubmit(). Must be set before prepareSubmit() is called. |
const std::string & | boundary const | Returns the MIME boundary used for writing multipart form data. |
ConnectionStream & | connection | The associated HTTP client connection. |
{#formwriter-1}
~FormWriter
virtual
virtual ~FormWriter()
Destroys the FormWriter.
{#addpart}
addPart
void addPart(const std::string & name, FormPart * part)
Adds a part or file attachment to the multipart form.
The FormWriter takes ownership of part and deletes it when done. Parts are only sent when the encoding is "multipart/form-data".
Parameters
-
nameForm field name for this part. -
partPart to add. Ownership is transferred.
{#start-10}
start
virtual
virtual void start()
Starts the sending thread.
{#stop-8}
stop
virtual
virtual void stop()
Stops the sending thread.
{#complete-1}
complete
const
bool complete() const
Returns true if the request is complete.
{#cancelled-1}
cancelled
const
bool cancelled() const
Returns true if the request is cancelled.
{#preparesubmit}
prepareSubmit
void prepareSubmit()
Prepares the outgoing HTTP request object for submitting the form.
{#calculatemultipartcontentlength}
calculateMultipartContentLength
uint64_t calculateMultipartContentLength()
Processes the entire form body and computes its total byte length. Only meaningful for multipart/form-data when not using chunked encoding.
Returns
Total content length in bytes.
{#writeurl}
writeUrl
void writeUrl(std::ostream & ostr)
Writes the complete "application/x-www-form-urlencoded" encoded body to ostr. All key-value pairs from the NVCollection base are percent-encoded and joined with '&'.
Parameters
ostrOutput stream to write to.
{#writemultipartchunk}
writeMultipartChunk
void writeMultipartChunk()
Writes the next pending multipart chunk to the connection. Non-blocking; intended to be called repeatedly from the event loop until all parts have been sent.
{#writeasync}
writeAsync
void writeAsync()
Writes the next message chunk from the background runner thread. Called by the Runner; do not call directly.
{#setencoding}
setEncoding
void setEncoding(const std::string & encoding)
Sets the MIME encoding used for submitting the form. Must be set before prepareSubmit() is called.
Parameters
encodingMIME type: ENCODING_URL or ENCODING_MULTIPART_FORM.
{#encoding}
encoding
const
const std::string & encoding() const
Returns the encoding used for posting the form.
{#setboundary}
setBoundary
void setBoundary(const std::string & boundary)
Sets the MIME boundary string used to delimit multipart form parts. If not set, a random boundary is generated by prepareSubmit(). Must be set before prepareSubmit() is called.
Parameters
boundaryBoundary string (without leading "--").
{#boundary}
boundary
const
const std::string & boundary() const
Returns the MIME boundary used for writing multipart form data.
{#connection-5}
connection
ConnectionStream & connection()
The associated HTTP client connection.
Public Static Attributes
| Return | Name | Description |
|---|---|---|
const char * | ENCODING_URL static | "application/x-www-form-urlencoded" |
const char * | ENCODING_MULTIPART_FORM static | "multipart/form-data" |
const char * | ENCODING_MULTIPART_RELATED static | "multipart/related" http://tools.ietf.org/html/rfc2387 |
{#encoding_url}
ENCODING_URL
static
const char * ENCODING_URL
"application/x-www-form-urlencoded"
{#encoding_multipart_form}
ENCODING_MULTIPART_FORM
static
const char * ENCODING_MULTIPART_FORM
"multipart/form-data"
{#encoding_multipart_related}
ENCODING_MULTIPART_RELATED
static
const char * ENCODING_MULTIPART_RELATED
"multipart/related" http://tools.ietf.org/html/rfc2387
Public Static Methods
| Return | Name | Description |
|---|---|---|
FormWriter * | create static | Creates a FormWriter for the given connection and encoding. |
{#create-7}
create
static
static FormWriter * create(ConnectionStream & conn, const std::string & encoding)
Creates a FormWriter for the given connection and encoding.
Encoding must be either "application/x-www-form-urlencoded" (which is the default) or "multipart/form-data".
Parameters
-
connThe HTTP connection stream to write form data to. -
encodingMIME encoding type.
Returns
Heap-allocated FormWriter. The caller owns the returned pointer.
Protected Attributes
| Return | Name | Description |
|---|---|---|
ConnectionStream & | _stream | |
std::shared_ptr< Runner > | _runner | |
std::string | _encoding | |
std::string | _boundary | |
PartQueue | _parts | |
uint64_t | _filesLength | |
int | _writeState | |
bool | _initial | |
bool | _complete |
{#_stream}
_stream
ConnectionStream & _stream
{#_runner}
_runner
std::shared_ptr< Runner > _runner
{#_encoding}
_encoding
std::string _encoding
{#_boundary}
_boundary
std::string _boundary
{#_parts}
_parts
PartQueue _parts
{#_fileslength}
_filesLength
uint64_t _filesLength
{#_writestate}
_writeState
int _writeState
{#_initial}
_initial
bool _initial
{#_complete-1}
_complete
bool _complete
Protected Methods
| Return | Name | Description |
|---|---|---|
FormWriter | Creates the FormWriter that uses the given encoding. | |
FormWriter | Deleted constructor. | |
FormWriter | Deleted constructor. | |
void | writePartHeader | Writes the message boundary std::string, followed by the message header to the output stream. |
void | writeEnd | Writes the final boundary std::string to the output stream. |
void | updateProgress virtual | Updates the upload progress via the associated ConnectionStream object. |
{#formwriter-2}
FormWriter
FormWriter(ConnectionStream & conn, std::shared_ptr< Runner > runner, const std::string & encoding)
Creates the FormWriter that uses the given encoding.
{#formwriter-3}
FormWriter
FormWriter(const FormWriter &) = delete
Deleted constructor.
{#formwriter-4}
FormWriter
FormWriter(FormWriter &&) = delete
Deleted constructor.
{#writepartheader}
writePartHeader
void writePartHeader(const NVCollection & header, std::ostream & ostr)
Writes the message boundary std::string, followed by the message header to the output stream.
{#writeend}
writeEnd
void writeEnd(std::ostream & ostr)
Writes the final boundary std::string to the output stream.
{#updateprogress}
updateProgress
virtual
virtual void updateProgress(int nread)
Updates the upload progress via the associated ConnectionStream object.
{#part}
Part
#include <icy/http/form.h>
Individual part within a multipart form submission.
Public Attributes
| Return | Name | Description |
|---|---|---|
std::string | name | |
std::unique_ptr< FormPart > | part |
{#name-5}
name
std::string name
{#part-1}
part
std::unique_ptr< FormPart > part
{#message}
Message
#include <icy/http/message.h>
Inherits:
NVCollectionSubclassed by:Request,Response
The base class for Request and Response.
Defines the common properties of all HTTP messages. These are version, content length, content type and transfer encoding.
Public Methods
| Return | Name | Description |
|---|---|---|
void | setVersion | Sets the HTTP version for this message. |
const std::string & | getVersion const | Returns the HTTP version for this message. |
void | setContentLength | Sets the Content-Length header. |
uint64_t | getContentLength const | Returns the content length for this message, which may be UNKNOWN_CONTENT_LENGTH if no Content-Length header is present. |
bool | hasContentLength const | Returns true if a Content-Length header is present. |
void | setTransferEncoding | Sets the transfer encoding for this message. |
const std::string & | getTransferEncoding const | Returns the transfer encoding used for this message. |
void | setChunkedTransferEncoding | If flag is true, sets the Transfer-Encoding header to chunked. Otherwise, removes the Transfer-Encoding header. |
bool | isChunkedTransferEncoding const | Returns true if the Transfer-Encoding header is set and its value is chunked. |
void | setContentType | Sets the content type for this message. |
const std::string & | getContentType const | Returns the content type for this message. |
void | setKeepAlive | Sets the value of the Connection header field. |
bool | getKeepAlive const | Returns true if |
void | write virtual const | Writes the message header to the given output stream. |
void | write virtual const | Writes the message header to the given output string. |
void | write virtual const | Writes the message header directly into a byte buffer. |
{#setversion-1}
setVersion
void setVersion(const std::string & version)
Sets the HTTP version for this message.
{#getversion-1}
getVersion
const
const std::string & getVersion() const
Returns the HTTP version for this message.
{#setcontentlength}
setContentLength
void setContentLength(uint64_t length)
Sets the Content-Length header.
If length is UNKNOWN_CONTENT_LENGTH, removes the Content-Length header.
{#getcontentlength}
getContentLength
const
uint64_t getContentLength() const
Returns the content length for this message, which may be UNKNOWN_CONTENT_LENGTH if no Content-Length header is present.
{#hascontentlength}
hasContentLength
const
bool hasContentLength() const
Returns true if a Content-Length header is present.
{#settransferencoding}
setTransferEncoding
void setTransferEncoding(const std::string & transferEncoding)
Sets the transfer encoding for this message.
The value should be either IDENTITY_TRANSFER_CODING or CHUNKED_TRANSFER_CODING.
{#gettransferencoding}
getTransferEncoding
const
const std::string & getTransferEncoding() const
Returns the transfer encoding used for this message.
Normally, this is the value of the Transfer-Encoding header field. If no such field is present, returns IDENTITY_TRANSFER_CODING.
{#setchunkedtransferencoding}
setChunkedTransferEncoding
void setChunkedTransferEncoding(bool flag)
If flag is true, sets the Transfer-Encoding header to chunked. Otherwise, removes the Transfer-Encoding header.
{#ischunkedtransferencoding}
isChunkedTransferEncoding
const
bool isChunkedTransferEncoding() const
Returns true if the Transfer-Encoding header is set and its value is chunked.
{#setcontenttype}
setContentType
void setContentType(const std::string & contentType)
Sets the content type for this message.
Specify NO_CONTENT_TYPE to remove the Content-Type header.
{#getcontenttype}
getContentType
const
const std::string & getContentType() const
Returns the content type for this message.
If no Content-Type header is present, returns UNKNOWN_CONTENT_TYPE.
{#setkeepalive-1}
setKeepAlive
void setKeepAlive(bool keepAlive)
Sets the value of the Connection header field.
The value is set to "Keep-Alive" if keepAlive is true, or to "Close" otherwise.
{#getkeepalive}
getKeepAlive
const
bool getKeepAlive() const
Returns true if
-
the message has a Connection header field and its value is "Keep-Alive"
-
the message is an HTTP/1.1 message and no Connection header is set Returns false otherwise.
{#write-6}
write
virtual const
virtual void write(std::ostream & ostr) const
Writes the message header to the given output stream.
The format is one name-value pair per line, with name and value separated by a colon and lines delimited by a carriage return and a linefeed character. See RFC 2822 for details.
{#write-7}
write
virtual const
virtual void write(std::string & str) const
Writes the message header to the given output string.
{#write-8}
write
virtual const
virtual void write(Buffer & buf) const
Writes the message header directly into a byte buffer.
Public Static Attributes
| Return | Name | Description |
|---|---|---|
const std::string | HTTP_1_0 static | |
const std::string | HTTP_1_1 static | |
const std::string | IDENTITY_TRANSFER_ENCODING static | |
const std::string | CHUNKED_TRANSFER_ENCODING static | |
const int | UNKNOWN_CONTENT_LENGTH static | |
const std::string | UNKNOWN_CONTENT_TYPE static | |
const std::string | CONTENT_LENGTH static | |
const std::string | CONTENT_TYPE static | |
const std::string | TRANSFER_ENCODING static | |
const std::string | CONNECTION static | |
const std::string | CONNECTION_KEEP_ALIVE static | |
const std::string | CONNECTION_CLOSE static | |
const std::string | EMPTY static |
{#http_1_0}
HTTP_1_0
static
const std::string HTTP_1_0
{#http_1_1}
HTTP_1_1
static
const std::string HTTP_1_1
{#identity_transfer_encoding}
IDENTITY_TRANSFER_ENCODING
static
const std::string IDENTITY_TRANSFER_ENCODING
{#chunked_transfer_encoding}
CHUNKED_TRANSFER_ENCODING
static
const std::string CHUNKED_TRANSFER_ENCODING
{#unknown_content_length}
UNKNOWN_CONTENT_LENGTH
static
const int UNKNOWN_CONTENT_LENGTH
{#unknown_content_type}
UNKNOWN_CONTENT_TYPE
static
const std::string UNKNOWN_CONTENT_TYPE
{#content_length}
CONTENT_LENGTH
static
const std::string CONTENT_LENGTH
{#content_type}
CONTENT_TYPE
static
const std::string CONTENT_TYPE
{#transfer_encoding}
TRANSFER_ENCODING
static
const std::string TRANSFER_ENCODING
{#connection-6}
CONNECTION
static
const std::string CONNECTION
{#connection_keep_alive}
CONNECTION_KEEP_ALIVE
static
const std::string CONNECTION_KEEP_ALIVE
{#connection_close}
CONNECTION_CLOSE
static
const std::string CONNECTION_CLOSE
{#empty}
EMPTY
static
const std::string EMPTY
Protected Attributes
| Return | Name | Description |
|---|---|---|
std::string | _version |
{#_version-1}
_version
std::string _version
Protected Methods
| Return | Name | Description |
|---|---|---|
Message | Creates the Message with version HTTP/1.0. | |
Message | Creates the Message and sets the version. | |
~Message virtual | Destroys the Message. |
{#message-1}
Message
Message()
Creates the Message with version HTTP/1.0.
{#message-2}
Message
Message(const std::string & version)
Creates the Message and sets the version.
{#message-3}
~Message
virtual
virtual ~Message()
Destroys the Message.
{#multipartadapter}
MultipartAdapter
#include <icy/http/packetizers.h>
Inherits:
PacketProcessor
HTTP multipart encoding adapter for multipart/x-mixed-replace streaming.
Public Attributes
| Return | Name | Description |
|---|---|---|
Connection::Ptr | connection | HTTP connection for sending the initial response header. |
std::string | contentType | Content-Type of each part (e.g. "image/jpeg"). |
bool | isBase64 | If true, adds "Content-Transfer-Encoding: base64" to each part. |
bool | initial | True until the first chunk is processed and the boundary header emitted. |
PacketSignal | emitter |
{#connection-7}
connection
Connection::Ptr connection
HTTP connection for sending the initial response header.
{#contenttype-2}
contentType
std::string contentType
Content-Type of each part (e.g. "image/jpeg").
{#isbase64}
isBase64
bool isBase64
If true, adds "Content-Transfer-Encoding: base64" to each part.
{#initial-1}
initial
bool initial
True until the first chunk is processed and the boundary header emitted.
{#emitter-7}
emitter
PacketSignal emitter
Public Methods
| Return | Name | Description |
|---|---|---|
MultipartAdapter inline | Creates a MultipartAdapter that sends headers through the given connection. The per-part content type is read from the connection's outgoing header. | |
MultipartAdapter inline | Creates a MultipartAdapter that emits its own raw HTTP/1.1 200 response header. Use this when no Connection object is available. | |
void | emitHeader virtual inline | Emits the initial HTTP/1.1 200 OK response with Content-Type multipart/x-mixed-replace. If a connection is set, headers are written through it; otherwise a raw response string is emitted. |
void | emitChunkHeader virtual inline | Emits the MIME boundary and per-part headers (Content-Type, optionally Content-Transfer-Encoding) for the next multipart chunk. |
void | process virtual inline | Wraps the incoming packet as a multipart chunk and emits it downstream. Emits the multipart HTTP response headers on the first call. |
{#multipartadapter-1}
MultipartAdapter
inline
inline MultipartAdapter(Connection::Ptr connection, bool base64)
Creates a MultipartAdapter that sends headers through the given connection. The per-part content type is read from the connection's outgoing header.
Parameters
-
connectionHTTP connection to use for sending the initial multipart header. -
[base64](base.md#base64)If true, indicates parts are base64-encoded.
{#multipartadapter-2}
MultipartAdapter
inline
inline MultipartAdapter(const std::string & contentType, bool base64)
Creates a MultipartAdapter that emits its own raw HTTP/1.1 200 response header. Use this when no Connection object is available.
Parameters
-
contentTypeContent-Type for each multipart part. -
[base64](base.md#base64)If true, indicates parts are base64-encoded.
{#emitheader-1}
emitHeader
virtual inline
virtual inline void emitHeader()
Emits the initial HTTP/1.1 200 OK response with Content-Type multipart/x-mixed-replace. If a connection is set, headers are written through it; otherwise a raw response string is emitted.
{#emitchunkheader}
emitChunkHeader
virtual inline
virtual inline void emitChunkHeader()
Emits the MIME boundary and per-part headers (Content-Type, optionally Content-Transfer-Encoding) for the next multipart chunk.
{#process-6}
process
virtual inline
virtual inline void process(IPacket & packet)
Wraps the incoming packet as a multipart chunk and emits it downstream. Emits the multipart HTTP response headers on the first call.
Parameters
packetPacket containing the raw payload data.
{#parser-1}
Parser
#include <icy/http/parser.h>
HTTP request/response parser using the llhttp library.
Public Methods
| Return | Name | Description |
|---|---|---|
Parser | Creates a response parser. The response object is populated as data is parsed. | |
Parser | Creates a request parser. The request object is populated as data is parsed. | |
Parser | Creates a parser of the given type without binding a message object. | |
Parser | Deleted constructor. | |
Parser | Deleted constructor. | |
ParseResult | parse | Feeds a buffer of raw HTTP data into the parser. |
void | reset | Reset the internal state (reinitialises llhttp). Safe to call externally, NOT from inside llhttp callbacks. |
void | resetState | Reset internal flags without reinitialising llhttp. Safe to call from inside llhttp callbacks (e.g. on_message_begin). |
bool | complete const | Returns true if parsing is complete, either in success or error. |
bool | upgrade const | Returns true if the connection should be upgraded. |
llhttp_type_t | type const inline | Returns the parser type (HTTP_REQUEST or HTTP_RESPONSE). |
void | setRequest | Binds an HTTP request object to populate during parsing. Must only be called when no message is currently set and type is HTTP_REQUEST. |
void | setResponse | Binds an HTTP response object to populate during parsing. Must only be called when no message is currently set and type is HTTP_RESPONSE. |
void | setObserver | Sets the observer that receives parser events. |
void | clearMessage | Clear request/response pointers so they can be re-set. Used when resetting a pooled connection for reuse. |
http::Message * | message | Returns the currently bound message (request or response), or nullptr. |
ParserObserver * | observer const | Returns the current parser observer, or nullptr if none is set. |
{#parser-2}
Parser
Parser(http::Response * response)
Creates a response parser. The response object is populated as data is parsed.
Parameters
responseHTTP response object to populate.
{#parser-3}
Parser
Parser(http::Request * request)
Creates a request parser. The request object is populated as data is parsed.
Parameters
requestHTTP request object to populate.
{#parser-4}
Parser
Parser(llhttp_type_t type)
Creates a parser of the given type without binding a message object.
Parameters
typeEither HTTP_REQUEST or HTTP_RESPONSE.
{#parser-5}
Parser
Parser(const Parser &) = delete
Deleted constructor.
{#parser-6}
Parser
Parser(Parser &&) = delete
Deleted constructor.
{#parse}
parse
ParseResult parse(const char * data, size_t length)
Feeds a buffer of raw HTTP data into the parser.
May be called multiple times for streaming data. The parser state persists between calls. On completion or error, the observer is notified.
Parameters
-
dataPointer to the input data buffer. -
lengthNumber of bytes in the buffer.
Returns
Structured parse result including bytes consumed and terminal state.
{#reset-10}
reset
void reset()
Reset the internal state (reinitialises llhttp). Safe to call externally, NOT from inside llhttp callbacks.
{#resetstate}
resetState
void resetState()
Reset internal flags without reinitialising llhttp. Safe to call from inside llhttp callbacks (e.g. on_message_begin).
{#complete-2}
complete
const
bool complete() const
Returns true if parsing is complete, either in success or error.
{#upgrade}
upgrade
const
bool upgrade() const
Returns true if the connection should be upgraded.
{#type-9}
type
const inline
inline llhttp_type_t type() const
Returns the parser type (HTTP_REQUEST or HTTP_RESPONSE).
{#setrequest}
setRequest
void setRequest(http::Request * request)
Binds an HTTP request object to populate during parsing. Must only be called when no message is currently set and type is HTTP_REQUEST.
Parameters
requestThe request object to populate.
{#setresponse}
setResponse
void setResponse(http::Response * response)
Binds an HTTP response object to populate during parsing. Must only be called when no message is currently set and type is HTTP_RESPONSE.
Parameters
responseThe response object to populate.
{#setobserver}
setObserver
void setObserver(ParserObserver * observer)
Sets the observer that receives parser events.
Parameters
observerObserver to notify. May be nullptr to clear.
{#clearmessage}
clearMessage
void clearMessage()
Clear request/response pointers so they can be re-set. Used when resetting a pooled connection for reuse.
{#message-4}
message
http::Message * message()
Returns the currently bound message (request or response), or nullptr.
{#observer}
observer
const
ParserObserver * observer() const
Returns the current parser observer, or nullptr if none is set.
Protected Attributes
| Return | Name | Description |
|---|---|---|
ParserObserver * | _observer | |
http::Request * | _request | |
http::Response * | _response | |
http::Message * | _message | |
llhttp_t | _parser | |
llhttp_settings_t | _settings | |
llhttp_type_t | _type | |
bool | _wasHeaderValue | |
std::string | _lastHeaderField | |
std::string | _lastHeaderValue | |
bool | _complete | |
bool | _upgrade | |
Error | _error | |
ParseResult | _lastResult | |
MessageScratch | _scratch |
{#_observer}
_observer
ParserObserver * _observer
{#_request-1}
_request
http::Request * _request
{#_response-1}
_response
http::Response * _response
{#_message}
_message
http::Message * _message
{#_parser-1}
_parser
llhttp_t _parser
{#_settings}
_settings
llhttp_settings_t _settings
{#_type}
_type
llhttp_type_t _type
{#_washeadervalue}
_wasHeaderValue
bool _wasHeaderValue
{#_lastheaderfield}
_lastHeaderField
std::string _lastHeaderField
{#_lastheadervalue}
_lastHeaderValue
std::string _lastHeaderValue
{#_complete-2}
_complete
bool _complete
{#_upgrade}
_upgrade
bool _upgrade
{#_error-3}
_error
Error _error
{#_lastresult}
_lastResult
ParseResult _lastResult
{#_scratch}
_scratch
MessageScratch _scratch
Protected Methods
| Return | Name | Description |
|---|---|---|
void | init | |
void | clearBoundMessage | |
void | storeHeader | |
void | applyScratchToBoundMessage | |
void | onHeader | Callbacks. |
void | onHeadersEnd | |
void | onBody | |
void | onMessageEnd | |
void | onError |
{#init-8}
init
void init()
{#clearboundmessage}
clearBoundMessage
void clearBoundMessage()
{#storeheader}
storeHeader
void storeHeader(std::string name, std::string value)
{#applyscratchtoboundmessage}
applyScratchToBoundMessage
void applyScratchToBoundMessage()
{#onheader}
onHeader
void onHeader(std::string name, std::string value)
Callbacks.
{#onheadersend}
onHeadersEnd
void onHeadersEnd()
{#onbody}
onBody
void onBody(const char * buf, size_t len)
{#onmessageend}
onMessageEnd
void onMessageEnd()
{#onerror-3}
onError
void onError(llhttp_errno_t errnum, const std::string & message)
{#messagescratch}
MessageScratch
#include <icy/http/parser.h>
Public Attributes
| Return | Name | Description |
|---|---|---|
std::string | version | |
std::string | method | |
std::string | uri | |
std::string | reason | |
http::StatusCode | status | |
std::vector< std::pair< std::string, std::string > > | headers |
{#version-2}
version
std::string version
{#method-1}
method
std::string method
{#uri}
uri
std::string uri
{#reason}
reason
std::string reason
{#status-2}
status
http::StatusCode status =
{#headers-2}
headers
std::vector< std::pair< std::string, std::string > > headers
Public Methods
| Return | Name | Description |
|---|---|---|
void | reset inline |
{#reset-11}
reset
inline
inline void reset()
{#parseresult}
ParseResult
#include <icy/http/parser.h>
Public Attributes
| Return | Name | Description |
|---|---|---|
size_t | bytesConsumed | |
bool | messageComplete | |
bool | upgrade | |
Error | error |
{#bytesconsumed}
bytesConsumed
size_t bytesConsumed = 0
{#messagecomplete}
messageComplete
bool messageComplete = false
{#upgrade-1}
upgrade
bool upgrade = false
{#error-11}
error
Error error
Public Methods
| Return | Name | Description |
|---|---|---|
bool | ok const inline |
{#ok}
ok
const inline
inline bool ok() const
{#parserobserver}
ParserObserver
#include <icy/http/parser.h>
Subclassed by:
ConnectionAdapter
Abstract observer interface for HTTP parser events.
Public Methods
| Return | Name | Description |
|---|---|---|
void | onParserHeader | Called for each parsed HTTP header name/value pair. |
void | onParserHeadersEnd | Called when all HTTP headers have been parsed. |
void | onParserChunk | Called for each chunk of body data received. |
void | onParserEnd | Called when the HTTP message is fully parsed. |
void | onParserError | Called when a parse error occurs. |
{#onparserheader-1}
onParserHeader
void onParserHeader(const std::string & name, const std::string & value)
Called for each parsed HTTP header name/value pair.
Parameters
-
nameHeader field name. -
valueHeader field value.
{#onparserheadersend-1}
onParserHeadersEnd
void onParserHeadersEnd(bool upgrade)
Called when all HTTP headers have been parsed.
Parameters
upgradeTrue if the connection should be upgraded (e.g. to WebSocket).
{#onparserchunk-1}
onParserChunk
void onParserChunk(const char * data, size_t len)
Called for each chunk of body data received.
Parameters
-
dataPointer to the body data chunk. -
lenLength of the chunk in bytes.
{#onparserend-1}
onParserEnd
void onParserEnd()
Called when the HTTP message is fully parsed.
{#onparsererror-1}
onParserError
void onParserError(const Error & err)
Called when a parse error occurs.
Parameters
errError details from llhttp.
{#progresssignal}
ProgressSignal
#include <icy/http/connection.h>
Inherits:
Signal< void(const double &)>
HTTP progress signal for upload and download progress notifications.
Emits a double in the range [0, 100] as data is transferred. Set total to the expected byte count before calling [update()](#update-1).
Public Attributes
| Return | Name | Description |
|---|---|---|
void * | sender | Optional context pointer identifying the sender. |
uint64_t | current | Bytes transferred so far. |
uint64_t | total | Total expected bytes (from Content-Length). |
{#sender-1}
sender
void * sender
Optional context pointer identifying the sender.
{#current-1}
current
uint64_t current
Bytes transferred so far.
{#total-1}
total
uint64_t total
Total expected bytes (from Content-Length).
Public Methods
| Return | Name | Description |
|---|---|---|
ProgressSignal inline | ||
double | progress const inline | Returns the current transfer progress as a percentage (0-100). |
void | update inline | Advances the progress counter by nread bytes and emits the updated percentage. |
{#progresssignal-1}
ProgressSignal
inline
inline ProgressSignal()
{#progress}
progress
const inline
inline double progress() const
Returns the current transfer progress as a percentage (0-100).
{#update-1}
update
inline
inline void update(int nread)
Advances the progress counter by nread bytes and emits the updated percentage.
Parameters
nreadNumber of bytes just transferred.
Exceptions
std::runtime_errorif current would exceed total.
{#request-4}
Request
#include <icy/http/request.h>
Inherits:
Message
HTTP request message with method, URI, headers, and optional body.
In addition to the properties common to all HTTP messages, an HTTP request has a method (e.g. GET, HEAD, POST, etc.) and a request URI.
Public Methods
| Return | Name | Description |
|---|---|---|
Request | Creates a GET / HTTP/1.1 HTTP request. | |
Request | Creates a GET / HTTP/1.x request with the given version (HTTP/1.0 or HTTP/1.1). | |
Request | Creates an HTTP/1.0 request with the given method and URI. | |
Request | Creates an HTTP request with the given method, URI and version. | |
~Request virtual | Destroys the Request. | |
void | setMethod | Sets the method. |
const std::string & | getMethod const | Returns the method. |
void | setURI | Sets the request URI. |
void | appendURI | Appends a fragment to the request URI. Used by the parser when llhttp splits the URL across callbacks. |
const std::string & | getURI const | Returns the request URI. |
void | setHost | Sets the value of the Host header field. |
void | setHost | Sets the value of the Host header field. |
const std::string & | getHost const | Returns the value of the Host header field. |
void | setCookies | Adds a Cookie header with the names and values from cookies. |
void | getCookies const | Fills cookies with the cookies extracted from the Cookie headers in the request. |
void | getURIParameters const | Returns the request URI parameters. |
bool | hasCredentials const | Returns true if the request contains authentication information in the form of an Authorization header. |
void | getCredentials const | Returns the authentication scheme and additional authentication information contained in this request. |
void | setCredentials | Sets the authentication scheme and information for this request. |
bool | hasProxyCredentials const | Returns true if the request contains proxy authentication information in the form of an Proxy-Authorization header. |
void | getProxyCredentials const | Returns the proxy authentication scheme and additional proxy authentication information contained in this request. |
void | setProxyCredentials | Sets the proxy authentication scheme and information for this request. |
void | write virtual const | Writes the HTTP request to the given output stream. |
void | write virtual const | Writes the HTTP request to the given output string. |
void | write virtual const | Writes the HTTP request directly into a byte buffer. |
{#request-5}
Request
Request()
Creates a GET / HTTP/1.1 HTTP request.
{#request-6}
Request
Request(const std::string & version)
Creates a GET / HTTP/1.x request with the given version (HTTP/1.0 or HTTP/1.1).
{#request-7}
Request
Request(const std::string & method, const std::string & uri)
Creates an HTTP/1.0 request with the given method and URI.
{#request-8}
Request
Request(const std::string & method, const std::string & uri, const std::string & version)
Creates an HTTP request with the given method, URI and version.
{#request-9}
~Request
virtual
virtual ~Request()
Destroys the Request.
{#setmethod}
setMethod
void setMethod(const std::string & method)
Sets the method.
{#getmethod}
getMethod
const
const std::string & getMethod() const
Returns the method.
{#seturi}
setURI
void setURI(std::string uri)
Sets the request URI.
{#appenduri}
appendURI
void appendURI(std::string_view uri)
Appends a fragment to the request URI. Used by the parser when llhttp splits the URL across callbacks.
{#geturi}
getURI
const
const std::string & getURI() const
Returns the request URI.
{#sethost}
setHost
void setHost(const std::string & host)
Sets the value of the Host header field.
{#sethost-1}
setHost
void setHost(const std::string & host, uint16_t port)
Sets the value of the Host header field.
If the given port number is a non-standard port number (other than 80 or 443), it is included in the Host header field.
{#gethost}
getHost
const
const std::string & getHost() const
Returns the value of the Host header field.
Throws a NotFoundException if the request does not have a Host header field.
{#setcookies}
setCookies
void setCookies(const NVCollection & cookies)
Adds a Cookie header with the names and values from cookies.
{#getcookies}
getCookies
const
void getCookies(NVCollection & cookies) const
Fills cookies with the cookies extracted from the Cookie headers in the request.
{#geturiparameters}
getURIParameters
const
void getURIParameters(NVCollection & params) const
Returns the request URI parameters.
{#hascredentials}
hasCredentials
const
bool hasCredentials() const
Returns true if the request contains authentication information in the form of an Authorization header.
{#getcredentials}
getCredentials
const
void getCredentials(std::string & scheme, std::string & authInfo) const
Returns the authentication scheme and additional authentication information contained in this request.
Throws a std::exception if no authentication information is contained in the request.
{#setcredentials}
setCredentials
void setCredentials(std::string_view scheme, std::string_view authInfo)
Sets the authentication scheme and information for this request.
{#hasproxycredentials}
hasProxyCredentials
const
bool hasProxyCredentials() const
Returns true if the request contains proxy authentication information in the form of an Proxy-Authorization header.
{#getproxycredentials}
getProxyCredentials
const
void getProxyCredentials(std::string & scheme, std::string & authInfo) const
Returns the proxy authentication scheme and additional proxy authentication information contained in this request.
Throws a std::exception if no proxy authentication information is contained in the request.
{#setproxycredentials}
setProxyCredentials
void setProxyCredentials(std::string_view scheme, std::string_view authInfo)
Sets the proxy authentication scheme and information for this request.
{#write-9}
write
virtual const
virtual void write(std::ostream & ostr) const
Writes the HTTP request to the given output stream.
{#write-10}
write
virtual const
virtual void write(std::string & str) const
Writes the HTTP request to the given output string.
{#write-11}
write
virtual const
virtual void write(Buffer & buf) const
Writes the HTTP request directly into a byte buffer.
Protected Methods
| Return | Name | Description |
|---|---|---|
void | getCredentials const | Returns the authentication scheme and additional authentication information contained in the given header of request. |
void | setCredentials | Writes the authentication scheme and information for this request to the given header. |
{#getcredentials-1}
getCredentials
const
void getCredentials(const std::string & header, std::string & scheme, std::string & authInfo) const
Returns the authentication scheme and additional authentication information contained in the given header of request.
Throws a NotAuthenticatedException if no authentication information is contained in the request.
{#setcredentials-1}
setCredentials
void setCredentials(const std::string & header, std::string_view scheme, std::string_view authInfo)
Writes the authentication scheme and information for this request to the given header.
Private Attributes
| Return | Name | Description |
|---|---|---|
std::string | _method | |
std::string | _uri |
{#_method}
_method
std::string _method
{#_uri}
_uri
std::string _uri
{#response-1}
Response
#include <icy/http/response.h>
Inherits:
Message
HTTP response message with status, reason phrase, headers, and body metadata.
Public Methods
| Return | Name | Description |
|---|---|---|
Response | Creates the Response with OK status. | |
Response | Creates the Response with the given status and reason phrase. | |
Response | Creates the Response with the given version, status and reason phrase. | |
Response | Creates the Response with the given status and an appropriate reason phrase. | |
Response | Creates the Response with the given version, status and an appropriate reason phrase. | |
~Response virtual | Destroys the Response. | |
void | setStatus | Sets the HTTP status code. |
StatusCode | getStatus const | Returns the HTTP status code. |
void | setReason | Sets the HTTP reason phrase. |
const std::string & | getReason const | Returns the HTTP reason phrase. |
void | setStatusAndReason | Sets the HTTP status code and reason phrase. |
void | setDate | Sets the Date header to the given date/time value. |
Timestamp | getDate const | Returns the value of the Date header. |
void | addCookie | Adds the cookie to the response by adding a Set-Cookie header. |
void | getCookies const | Returns a vector with all the cookies set in the response header. |
void | write virtual const | Writes the HTTP response headers to the given output stream. |
void | write virtual const | Writes the HTTP response headers to the given output string. |
void | write virtual const | Writes the HTTP response headers directly into a byte buffer. |
bool | success virtual const | Returns true if the HTTP response code was successful (< 400). |
{#response-2}
Response
Response()
Creates the Response with OK status.
{#response-3}
Response
Response(StatusCode status, const std::string & reason)
Creates the Response with the given status and reason phrase.
{#response-4}
Response
Response(const std::string & version, StatusCode status, const std::string & reason)
Creates the Response with the given version, status and reason phrase.
{#response-5}
Response
Response(StatusCode status)
Creates the Response with the given status and an appropriate reason phrase.
{#response-6}
Response
Response(const std::string & version, StatusCode status)
Creates the Response with the given version, status and an appropriate reason phrase.
{#response-7}
~Response
virtual
virtual ~Response()
Destroys the Response.
{#setstatus}
setStatus
void setStatus(StatusCode status)
Sets the HTTP status code.
The reason phrase is set according to the status code.
{#getstatus}
getStatus
const
StatusCode getStatus() const
Returns the HTTP status code.
{#setreason}
setReason
void setReason(const std::string & reason)
Sets the HTTP reason phrase.
{#getreason}
getReason
const
const std::string & getReason() const
Returns the HTTP reason phrase.
{#setstatusandreason}
setStatusAndReason
void setStatusAndReason(StatusCode status, const std::string & reason)
Sets the HTTP status code and reason phrase.
{#setdate}
setDate
void setDate(const Timestamp & dateTime)
Sets the Date header to the given date/time value.
{#getdate}
getDate
const
Timestamp getDate() const
Returns the value of the Date header.
{#addcookie}
addCookie
void addCookie(const Cookie & cookie)
Adds the cookie to the response by adding a Set-Cookie header.
{#getcookies-1}
getCookies
const
void getCookies(std::vector< Cookie > & cookies) const
Returns a vector with all the cookies set in the response header.
May throw an exception in case of a malformed Set-Cookie header.
{#write-12}
write
virtual const
virtual void write(std::ostream & ostr) const
Writes the HTTP response headers to the given output stream.
{#write-13}
write
virtual const
virtual void write(std::string & str) const
Writes the HTTP response headers to the given output string.
{#write-14}
write
virtual const
virtual void write(Buffer & buf) const
Writes the HTTP response headers directly into a byte buffer.
{#success}
success
virtual const
virtual bool success() const
Returns true if the HTTP response code was successful (< 400).
Private Attributes
| Return | Name | Description |
|---|---|---|
StatusCode | _status | |
std::string | _reason |
{#_status}
_status
StatusCode _status
{#_reason}
_reason
std::string _reason
{#server}
Server
#include <icy/http/server.h>
Inherits:
SocketAdapter
HTTP server implementation.
This HTTP server is not strictly standards compliant. It was created to be a fast (nocopy where possible) solution for streaming media to web browsers.
Public Attributes
| Return | Name | Description |
|---|---|---|
LocalSignal< void(ServerConnection::Ptr)> | Connection | Signals when a new connection has been created. A reference to the new connection object is provided. |
LocalSignal< void()> | Shutdown | Signals when the server is shutting down. |
{#connection-8}
Connection
LocalSignal< void(ServerConnection::Ptr)> Connection
Signals when a new connection has been created. A reference to the new connection object is provided.
{#shutdown-7}
Shutdown
LocalSignal< void()> Shutdown
Signals when the server is shutting down.
Public Methods
| Return | Name | Description |
|---|---|---|
Server | Constructs an HTTP server on the given host and port using an internally created TCP socket. | |
Server | Constructs an HTTP server on the given address using an internally created TCP socket. | |
Server | Constructs an HTTP server on the given host and port using a caller-supplied socket. Useful for HTTPS by passing an SSLSocket. The event loop is derived from the socket. | |
Server | Constructs an HTTP server on the given address using a caller-supplied socket. The event loop is derived from the socket. | |
void | start | Start the HTTP server. |
void | stop | Stop the HTTP server. |
void | setReusePort inline | Enable SO_REUSEPORT for multicore server instances. Must be called before start(). Allows multiple server instances to bind the same address:port with kernel-level load balancing (Linux 3.9+). |
void | setMaxPooledConnections inline | Set the maximum number of pooled connections (default 128). Set to 0 to disable connection pooling entirely. |
void | setKeepAliveTimeout inline | Set the keep-alive idle timeout in seconds (default 30). Connections idle longer than this are closed by the timer. Set to 0 to disable idle timeout. |
size_t | connectionCount const inline | Return the number of active connections (all states). |
net::Address & | address | Return the server bind address. |
const DateCache & | dateCache const inline | Return the cached Date header for use in responses. |
{#server-1}
Server
Server(const std::string & host, short port, uv::Loop * loop, std::unique_ptr< ServerConnectionFactory > factory)
Constructs an HTTP server on the given host and port using an internally created TCP socket.
Parameters
-
hostBind address (e.g. "0.0.0.0" or "127.0.0.1"). -
portTCP port to listen on. -
loopEvent loop to use. Defaults to the default libuv loop. -
factoryConnection and responder factory. Defaults to the base factory.
{#server-2}
Server
Server(const net::Address & address, uv::Loop * loop, std::unique_ptr< ServerConnectionFactory > factory)
Constructs an HTTP server on the given address using an internally created TCP socket.
Parameters
-
addressBind address and port. -
loopEvent loop to use. Defaults to the default libuv loop. -
factoryConnection and responder factory.
{#server-3}
Server
Server(const std::string & host, short port, net::TCPSocket::Ptr socket, std::unique_ptr< ServerConnectionFactory > factory)
Constructs an HTTP server on the given host and port using a caller-supplied socket. Useful for HTTPS by passing an SSLSocket. The event loop is derived from the socket.
Parameters
-
hostBind address. -
portTCP port to listen on. -
socketPre-created socket (e.g. SSLSocket for HTTPS). -
factoryConnection and responder factory.
{#server-4}
Server
Server(const net::Address & address, net::TCPSocket::Ptr socket, std::unique_ptr< ServerConnectionFactory > factory)
Constructs an HTTP server on the given address using a caller-supplied socket. The event loop is derived from the socket.
Parameters
-
addressBind address and port. -
socketPre-created socket (e.g. SSLSocket for HTTPS). -
factoryConnection and responder factory.
{#start-11}
start
void start()
Start the HTTP server.
{#stop-9}
stop
void stop()
Stop the HTTP server.
{#setreuseport-1}
setReusePort
inline
inline void setReusePort(bool enable)
Enable SO_REUSEPORT for multicore server instances. Must be called before start(). Allows multiple server instances to bind the same address:port with kernel-level load balancing (Linux 3.9+).
{#setmaxpooledconnections}
setMaxPooledConnections
inline
inline void setMaxPooledConnections(size_t n)
Set the maximum number of pooled connections (default 128). Set to 0 to disable connection pooling entirely.
{#setkeepalivetimeout}
setKeepAliveTimeout
inline
inline void setKeepAliveTimeout(int seconds)
Set the keep-alive idle timeout in seconds (default 30). Connections idle longer than this are closed by the timer. Set to 0 to disable idle timeout.
{#connectioncount}
connectionCount
const inline
inline size_t connectionCount() const
Return the number of active connections (all states).
{#address-11}
address
net::Address & address()
Return the server bind address.
{#datecache-1}
dateCache
const inline
inline const DateCache & dateCache() const
Return the cached Date header for use in responses.
Protected Attributes
| Return | Name | Description |
|---|---|---|
uv::Loop * | _loop | |
net::Address | _address | |
net::TCPSocket::Ptr | _socket | |
Timer | _timer | |
std::unique_ptr< ServerConnectionFactory > | _factory | |
std::unordered_map< ServerConnection *, ServerConnection::Ptr > | _connections | |
ConnectionPool | _pool | |
DateCache | _dateCache | |
int | _keepAliveTimeout | |
bool | _reusePort |
{#_loop-1}
_loop
uv::Loop * _loop
{#_address}
_address
net::Address _address
{#_socket-2}
_socket
net::TCPSocket::Ptr _socket
{#_timer}
_timer
Timer _timer
{#_factory}
_factory
std::unique_ptr< ServerConnectionFactory > _factory
{#_connections-1}
_connections
std::unordered_map< ServerConnection *, ServerConnection::Ptr > _connections
{#_pool-1}
_pool
ConnectionPool _pool
{#_datecache}
_dateCache
DateCache _dateCache
{#_keepalivetimeout}
_keepAliveTimeout
int _keepAliveTimeout {30}
{#_reuseport}
_reusePort
bool _reusePort {false}
Protected Methods
| Return | Name | Description |
|---|---|---|
std::unique_ptr< ServerResponder > | createResponder | |
void | onClientSocketAccept | |
void | onConnectionReady | |
void | onConnectionClose | |
bool | onSocketClose virtual | Called when the socket is closed. Forwards the event to all registered receivers in priority order. |
void | onTimer | |
uv::Loop * | loop const inline | Return the event loop this server runs on. |
{#createresponder}
createResponder
std::unique_ptr< ServerResponder > createResponder(ServerConnection & conn)
{#onclientsocketaccept}
onClientSocketAccept
void onClientSocketAccept(const net::TCPSocket::Ptr & socket)
{#onconnectionready}
onConnectionReady
void onConnectionReady(ServerConnection & conn)
{#onconnectionclose-1}
onConnectionClose
void onConnectionClose(ServerConnection & conn)
{#onsocketclose-3}
onSocketClose
virtual
virtual bool onSocketClose(net::Socket & socket)
Called when the socket is closed. Forwards the event to all registered receivers in priority order.
Parameters
socketThe socket that was closed.
Returns
true to stop propagation to subsequent receivers.
{#ontimer}
onTimer
void onTimer()
{#loop-6}
loop
const inline
inline uv::Loop * loop() const
Return the event loop this server runs on.
{#serverconnection}
ServerConnection
#include <icy/http/server.h>
Inherits:
Connection
HTTP server connection.
Public Attributes
| Return | Name | Description |
|---|---|---|
LocalSignal< void(ServerConnection &, const MutableBuffer &)> | Payload | Signals when raw data is received. |
LocalSignal< void(ServerConnection &)> | Close | Signals when the connection is closed. |
{#payload-1}
Payload
LocalSignal< void(ServerConnection &, const MutableBuffer &)> Payload
Signals when raw data is received.
{#close-21}
Close
LocalSignal< void(ServerConnection &)> Close
Signals when the connection is closed.
Public Methods
| Return | Name | Description |
|---|---|---|
ServerConnection | Creates a ServerConnection attached to the given server and socket. | |
Server & | server | Returns the owning Server instance. |
ServerConnectionState | state const inline | Returns the current server-side connection state. |
ServerConnectionMode | mode const inline | Returns the current transport mode. |
bool | upgraded const inline | Returns true if the connection has been upgraded (e.g. to WebSocket). |
bool | streaming const inline | Returns true if the connection is in long-lived streaming mode. |
bool | idleTimeoutEnabled const | Returns true if the server idle timer is allowed to reap this connection. |
bool | reusableForPool const | Returns true if the closed connection can be returned to the reuse pool. |
void | markActive virtual inline | Refresh the idle timer. |
void | reset | Reset this connection for reuse with a new socket. Called by the connection pool to avoid allocating a new ServerConnection. |
void | touch inline | Update the last activity timestamp. |
double | idleSeconds const inline | Return seconds since last activity. |
void | beginStreaming virtual | Explicitly mark the response as long-lived streaming. Streaming connections are excluded from the keep-alive idle reaper. |
void | endStreaming virtual | Exit streaming mode and return to the given HTTP state. |
void | endStreaming | |
ssize_t | sendHeader virtual | Send the outgoing HTTP header. |
void | close virtual | Close the connection with an explicit terminal state transition. |
{#serverconnection-1}
ServerConnection
ServerConnection(Server & server, net::TCPSocket::Ptr socket)
Creates a ServerConnection attached to the given server and socket.
Parameters
-
serverThe owning HTTP server instance. -
socketThe accepted TCP socket for this connection.
{#server-5}
server
Server & server()
Returns the owning Server instance.
{#state-1}
state
const inline
inline ServerConnectionState state() const
Returns the current server-side connection state.
{#mode-1}
mode
const inline
inline ServerConnectionMode mode() const
Returns the current transport mode.
{#upgraded}
upgraded
const inline
inline bool upgraded() const
Returns true if the connection has been upgraded (e.g. to WebSocket).
{#streaming}
streaming
const inline
inline bool streaming() const
Returns true if the connection is in long-lived streaming mode.
{#idletimeoutenabled}
idleTimeoutEnabled
const
bool idleTimeoutEnabled() const
Returns true if the server idle timer is allowed to reap this connection.
{#reusableforpool}
reusableForPool
const
bool reusableForPool() const
Returns true if the closed connection can be returned to the reuse pool.
{#markactive-1}
markActive
virtual inline
virtual inline void markActive()
Refresh the idle timer.
{#reset-12}
reset
void reset(net::TCPSocket::Ptr socket)
Reset this connection for reuse with a new socket. Called by the connection pool to avoid allocating a new ServerConnection.
{#touch}
touch
inline
inline void touch()
Update the last activity timestamp.
{#idleseconds}
idleSeconds
const inline
inline double idleSeconds() const
Return seconds since last activity.
{#beginstreaming-1}
beginStreaming
virtual
virtual void beginStreaming()
Explicitly mark the response as long-lived streaming. Streaming connections are excluded from the keep-alive idle reaper.
{#endstreaming-1}
endStreaming
virtual
virtual void endStreaming()
Exit streaming mode and return to the given HTTP state.
{#endstreaming-2}
endStreaming
void endStreaming(ServerConnectionState nextState)
{#sendheader-1}
sendHeader
virtual
virtual ssize_t sendHeader()
Send the outgoing HTTP header.
{#close-22}
close
virtual
virtual void close()
Close the connection with an explicit terminal state transition.
Protected Attributes
| Return | Name | Description |
|---|---|---|
Server & | _server | |
std::unique_ptr< ServerResponder > | _responder | |
std::time_t | _lastActivity | |
ServerConnectionState | _state | |
ServerConnectionMode | _mode |
{#_server}
_server
Server & _server
{#_responder}
_responder
std::unique_ptr< ServerResponder > _responder
{#_lastactivity}
_lastActivity
std::time_t _lastActivity {0}
{#_state-2}
_state
ServerConnectionState _state {}
{#_mode-2}
_mode
ServerConnectionMode _mode {}
Protected Methods
| Return | Name | Description |
|---|---|---|
void | onHeaders virtual | Called when the incoming HTTP headers have been fully parsed. |
void | onPayload virtual | Called for each chunk of incoming body data after headers are complete. |
void | onComplete virtual | Called when the incoming HTTP message is fully received. |
void | onClose virtual | Called when the connection is closed. |
http::Message * | incomingHeader virtual | Returns the incoming HTTP message header (request or response depending on role). |
http::Message * | outgoingHeader virtual | Returns the outgoing HTTP message header (request or response depending on role). |
void | setState | |
bool | requestHasBody const | |
bool | responseLooksStreaming const |
{#onheaders-2}
onHeaders
virtual
virtual void onHeaders()
Called when the incoming HTTP headers have been fully parsed.
{#onpayload-2}
onPayload
virtual
virtual void onPayload(const MutableBuffer & buffer)
Called for each chunk of incoming body data after headers are complete.
Parameters
bufferBuffer containing the received data chunk.
{#oncomplete-2}
onComplete
virtual
virtual void onComplete()
Called when the incoming HTTP message is fully received.
{#onclose-5}
onClose
virtual
virtual void onClose()
Called when the connection is closed.
{#incomingheader-2}
incomingHeader
virtual
virtual http::Message * incomingHeader()
Returns the incoming HTTP message header (request or response depending on role).
{#outgoingheader-2}
outgoingHeader
virtual
virtual http::Message * outgoingHeader()
Returns the outgoing HTTP message header (request or response depending on role).
{#setstate}
setState
void setState(ServerConnectionState state)
{#requesthasbody}
requestHasBody
const
bool requestHasBody() const
{#responselooksstreaming}
responseLooksStreaming
const
bool responseLooksStreaming() const
Public Types
| Name | Description |
|---|---|
Ptr |
{#ptr-13}
Ptr
std::shared_ptr< ServerConnection > Ptr()
{#serverconnectionfactory}
ServerConnectionFactory
#include <icy/http/server.h>
Factory for creating per-socket [ServerConnection](#serverconnection) and per-request [ServerResponder](#serverresponder) objects.
Public Methods
| Return | Name | Description |
|---|---|---|
ServerConnectionFactory | Defaulted constructor. | |
ServerConnection::Ptr | createConnection virtual inline | Creates the [ServerConnection](#serverconnection) wrapper for an accepted TCP socket. |
std::unique_ptr< ServerResponder > | createResponder virtual inline | Creates the responder for the current request on connection. |
{#serverconnectionfactory-1}
ServerConnectionFactory
ServerConnectionFactory() = default
Defaulted constructor.
{#createconnection-2}
createConnection
virtual inline
virtual inline ServerConnection::Ptr createConnection(Server & server, const net::TCPSocket::Ptr & socket)
Creates the [ServerConnection](#serverconnection) wrapper for an accepted TCP socket.
{#createresponder-1}
createResponder
virtual inline
virtual inline std::unique_ptr< ServerResponder > createResponder(ServerConnection & connection)
Creates the responder for the current request on connection.
{#serverresponder}
ServerResponder
#include <icy/http/server.h>
Base responder interface for handling one HTTP request on a server connection. Derived classes typically override [onRequest()](#onrequest) and optionally the streaming hooks.
Public Methods
| Return | Name | Description |
|---|---|---|
ServerResponder inline | Creates a ServerResponder for the given connection. | |
void | onHeaders virtual inline | Called when the incoming request headers have been parsed. |
void | onPayload virtual inline | Called for each chunk of incoming request body data. |
void | onRequest virtual inline | Called when the complete HTTP request has been received. Derived classes should write their response here. |
void | onClose virtual inline | Called when the connection is closed. |
ServerConnection & | connection inline | Returns the underlying server connection. |
Request & | request inline | Returns the current HTTP request from the underlying connection. |
Response & | response inline | Returns the current HTTP response from the underlying connection. |
{#serverresponder-1}
ServerResponder
inline
inline ServerResponder(ServerConnection & connection)
Creates a ServerResponder for the given connection.
Parameters
connectionThe server connection this responder handles.
{#onheaders-3}
onHeaders
virtual inline
virtual inline void onHeaders(Request & request)
Called when the incoming request headers have been parsed.
Parameters
requestThe parsed HTTP request with headers populated.
{#onpayload-3}
onPayload
virtual inline
virtual inline void onPayload(const MutableBuffer & body)
Called for each chunk of incoming request body data.
Parameters
bodyBuffer containing a chunk of the request body.
{#onrequest}
onRequest
virtual inline
virtual inline void onRequest(Request & request, Response & response)
Called when the complete HTTP request has been received. Derived classes should write their response here.
Parameters
-
requestThe fully received HTTP request. -
responseThe HTTP response to populate and send.
{#onclose-6}
onClose
virtual inline
virtual inline void onClose()
Called when the connection is closed.
{#connection-9}
connection
inline
inline ServerConnection & connection()
Returns the underlying server connection.
{#request-10}
request
inline
inline Request & request()
Returns the current HTTP request from the underlying connection.
{#response-8}
response
inline
inline Response & response()
Returns the current HTTP response from the underlying connection.
Protected Attributes
| Return | Name | Description |
|---|---|---|
ServerConnection & | _connection |
{#_connection-2}
_connection
ServerConnection & _connection
Private Methods
| Return | Name | Description |
|---|---|---|
ServerResponder | Deleted constructor. |
{#serverresponder-2}
ServerResponder
ServerResponder(const ServerResponder &) = delete
Deleted constructor.
{#stringpart}
StringPart
#include <icy/http/form.h>
Inherits:
FormPart
Form part backed by an in-memory string payload.
Public Methods
| Return | Name | Description |
|---|---|---|
StringPart | Creates a StringPart with the given data and default content type "application/octet-stream". | |
StringPart | Creates a StringPart with the given data and MIME content type. | |
~StringPart virtual | Destroys the StringPart. | |
bool | writeChunk virtual | Writes the string data as a single chunk to the FormWriter. |
void | write virtual | Writes the string data to the FormWriter. |
void | write virtual | Writes the string data to an output stream. |
uint64_t | length virtual const | Returns the byte length of the string data. |
{#stringpart-1}
StringPart
StringPart(const std::string & data)
Creates a StringPart with the given data and default content type "application/octet-stream".
Parameters
dataString data to send as this part.
{#stringpart-2}
StringPart
StringPart(const std::string & data, const std::string & contentType)
Creates a StringPart with the given data and MIME content type.
Parameters
-
dataString data to send as this part. -
contentTypeMIME type for this part.
{#stringpart-3}
~StringPart
virtual
virtual ~StringPart()
Destroys the StringPart.
{#writechunk-2}
writeChunk
virtual
virtual bool writeChunk(FormWriter & writer)
Writes the string data as a single chunk to the FormWriter.
Parameters
writerThe FormWriter to send data through.
Returns
false always (string data is sent in a single chunk).
{#write-15}
write
virtual
virtual void write(FormWriter & writer)
Writes the string data to the FormWriter.
Parameters
writerThe FormWriter to send data through.
{#write-16}
write
virtual
virtual void write(std::ostream & ostr)
Writes the string data to an output stream.
Parameters
ostrOutput stream to write to.
{#length-3}
length
virtual const
virtual uint64_t length() const
Returns the byte length of the string data.
Protected Attributes
| Return | Name | Description |
|---|---|---|
std::string | _data |
{#_data}
_data
std::string _data
{#url}
URL
#include <icy/http/url.h>
An RFC 3986 based URL parser. Constructors and assignment operators will throw a SyntaxException if the URL is invalid.
Public Methods
| Return | Name | Description |
|---|---|---|
URL | Creates an empty URL. | |
URL | Parses the URL from a null-terminated string. | |
URL | Parses the URL from a std::string. | |
URL | Constructs a URL from scheme and authority components. | |
URL | Constructs a URL from scheme, authority, and path+query+fragment. | |
URL | Constructs a URL from individual components. | |
URL | Defaulted constructor. | |
URL & | operator= | Assigns a URL from another URL instance. |
URL & | operator= | Assigns a URL from a null-terminated string. |
URL & | operator= | Assigns a URL from a std::string. |
bool | parse | Parses and assigns a URL from the given string view, resetting all components first. |
std::string | scheme const | Returns the URL scheme (e.g. "http", "https", "ws"). Always lowercase. |
std::string | userInfo const | Returns the user info component (e.g. "user:pass" from "http://user:pass@host/"). Returns an empty string if not present. |
std::string | host const | Returns the host component (e.g. "example.com"). Returns an empty string if not present. |
uint16_t | port const | Returns the port number. If no explicit port was in the URL, returns the default port for the scheme (80 for http, 443 for https), or 0 if the scheme is unknown. |
std::string | authority const | Returns the authority component (userinfo@host:port). Only includes components that are present. |
std::string | path const | Returns the path component (e.g. "/index.html"). Returns an empty string if not present. |
std::string | pathEtc const | Returns the path, query and fragment combined (e.g. "/path?q=1#frag"). |
std::string | query const | Returns the query string without the leading '?' (e.g. "key=value&foo=bar"). Returns an empty string if not present. |
std::string | fragment const | Returns the fragment identifier without the leading '#'. Returns an empty string if not present. |
bool | hasSchema const | Returns true if the URL has a scheme component. |
bool | hasUserInfo const | Returns true if the URL has a user info component. |
bool | hasHost const | Returns true if the URL has a host component. |
bool | hasPort const | Returns true if an explicit port was specified in the URL. |
bool | hasPath const | Returns true if the URL has a path component. |
bool | hasQuery const | Returns true if the URL has a query component. |
bool | hasFragment const | Returns true if the URL has a fragment component. |
bool | valid const | Returns true if the URL is non-empty and was successfully parsed. |
std::string | str const | Returns the original URL string as parsed. |
{#url-1}
URL
URL()
Creates an empty URL.
{#url-2}
URL
URL(const char * url)
Parses the URL from a null-terminated string.
Parameters
urlNull-terminated URL string to parse.
{#url-3}
URL
URL(const std::string & url)
Parses the URL from a std::string.
Parameters
urlURL string to parse.
{#url-4}
URL
URL(const std::string & scheme, const std::string & authority)
Constructs a URL from scheme and authority components.
Parameters
-
schemeURL scheme (e.g. "http", "https"). -
authorityHost and optional port (e.g. "example.com:8080").
{#url-5}
URL
URL(const std::string & scheme, const std::string & authority, const std::string & pathEtc)
Constructs a URL from scheme, authority, and path+query+fragment.
Parameters
-
schemeURL scheme (e.g. "http"). -
authorityHost and optional port. -
pathEtcPath, query and fragment combined (e.g. "/path?q=1#frag").
{#url-6}
URL
URL(const std::string & scheme, const std::string & authority, const std::string & path, const std::string & query, const std::string & fragment)
Constructs a URL from individual components.
Parameters
-
schemeURL scheme (e.g. "http"). -
authorityHost and optional port. -
pathURL path (e.g. "/index.html"). -
queryQuery string without leading '?' (e.g. "key=value"). -
fragmentFragment identifier without leading '#'.
{#url-7}
URL
URL(const URL &) = default
Defaulted constructor.
{#operator-15}
operator=
URL & operator=(const URL & uri)
Assigns a URL from another URL instance.
Parameters
uriSource URL to copy from.
Returns
Reference to this URL.
{#operator-16}
operator=
URL & operator=(const char * uri)
Assigns a URL from a null-terminated string.
Parameters
uriNull-terminated URL string to parse.
Returns
Reference to this URL.
{#operator-17}
operator=
URL & operator=(const std::string & uri)
Assigns a URL from a std::string.
Parameters
uriURL string to parse.
Returns
Reference to this URL.
{#parse-1}
parse
bool parse(std::string_view url, bool whiny)
Parses and assigns a URL from the given string view, resetting all components first.
Parameters
-
urlURL string to parse. -
whinyIf true, throws std::runtime_error on an invalid URL; otherwise returns false.
Returns
true if the URL was parsed successfully; false if invalid and whiny is false.
{#scheme}
scheme
const
std::string scheme() const
Returns the URL scheme (e.g. "http", "https", "ws"). Always lowercase.
{#userinfo}
userInfo
const
std::string userInfo() const
Returns the user info component (e.g. "user:pass" from "http://user:pass@host/"). Returns an empty string if not present.
{#host-1}
host
const
std::string host() const
Returns the host component (e.g. "example.com"). Returns an empty string if not present.
{#port-1}
port
const
uint16_t port() const
Returns the port number. If no explicit port was in the URL, returns the default port for the scheme (80 for http, 443 for https), or 0 if the scheme is unknown.
{#authority}
authority
const
std::string authority() const
Returns the authority component (userinfo@host:port). Only includes components that are present.
{#path}
path
const
std::string path() const
Returns the path component (e.g. "/index.html"). Returns an empty string if not present.
{#pathetc}
pathEtc
const
std::string pathEtc() const
Returns the path, query and fragment combined (e.g. "/path?q=1#frag").
{#query}
query
const
std::string query() const
Returns the query string without the leading '?' (e.g. "key=value&foo=bar"). Returns an empty string if not present.
{#fragment}
fragment
const
std::string fragment() const
Returns the fragment identifier without the leading '#'. Returns an empty string if not present.
{#hasschema}
hasSchema
const
bool hasSchema() const
Returns true if the URL has a scheme component.
{#hasuserinfo}
hasUserInfo
const
bool hasUserInfo() const
Returns true if the URL has a user info component.
{#hashost}
hasHost
const
bool hasHost() const
Returns true if the URL has a host component.
{#hasport}
hasPort
const
bool hasPort() const
Returns true if an explicit port was specified in the URL.
{#haspath}
hasPath
const
bool hasPath() const
Returns true if the URL has a path component.
{#hasquery}
hasQuery
const
bool hasQuery() const
Returns true if the URL has a query component.
{#hasfragment}
hasFragment
const
bool hasFragment() const
Returns true if the URL has a fragment component.
{#valid-1}
valid
const
bool valid() const
Returns true if the URL is non-empty and was successfully parsed.
{#str-1}
str
const
std::string str() const
Returns the original URL string as parsed.
Public Static Methods
| Return | Name | Description |
|---|---|---|
std::string | encode static | Percent-encodes a string per RFC 3986, preserving unreserved characters (A-Z, a-z, 0-9, '-', '_', '.', '~'). Equivalent to JavaScript's encodeURIComponent(). |
std::string | decode static | Decodes a percent-encoded string per RFC 3986. Equivalent to JavaScript's decodeURIComponent(). |
{#encode-21}
encode
static
static std::string encode(std::string_view str)
Percent-encodes a string per RFC 3986, preserving unreserved characters (A-Z, a-z, 0-9, '-', '_', '.', '~'). Equivalent to JavaScript's encodeURIComponent().
Parameters
strInput string to encode.
Returns
Percent-encoded string.
{#decode-10}
decode
static
static std::string decode(std::string_view str)
Decodes a percent-encoded string per RFC 3986. Equivalent to JavaScript's decodeURIComponent().
Parameters
strPercent-encoded input string.
Returns
Decoded string.
Protected Attributes
| Return | Name | Description |
|---|---|---|
std::string | _buf | |
std::string | _scheme | |
std::string | _userInfo | |
std::string | _host | |
uint16_t | _port | |
std::string | _path | |
std::string | _query | |
std::string | _fragment | |
bool | _hasPort |
{#_buf}
_buf
std::string _buf
{#_scheme}
_scheme
std::string _scheme
{#_userinfo}
_userInfo
std::string _userInfo
{#_host}
_host
std::string _host
{#_port}
_port
uint16_t _port
{#_path-2}
_path
std::string _path
{#_query}
_query
std::string _query
{#_fragment}
_fragment
std::string _fragment
{#_hasport}
_hasPort
bool _hasPort
{#datecache}
DateCache
#include <icy/http/server.h>
Caches the formatted Date header, updated once per second. Avoids per-request time formatting and string allocation.
Public Attributes
| Return | Name | Description |
|---|---|---|
char | buf | |
size_t | len | |
std::time_t | lastSecond |
{#buf}
buf
char buf {}
{#len}
len
size_t len = 0
{#lastsecond}
lastSecond
std::time_t lastSecond = 0
Public Methods
| Return | Name | Description |
|---|---|---|
void | update inline | Refreshes the cached Date header string if the current second has changed. No-op if called multiple times within the same second. |
const char * | data const inline | Returns a pointer to the formatted "Date: ...\r\n" header string. |
size_t | size const inline | Returns the byte length of the formatted Date header string. |
{#update}
update
inline
inline void update()
Refreshes the cached Date header string if the current second has changed. No-op if called multiple times within the same second.
{#data-2}
data
const inline
inline const char * data() const
Returns a pointer to the formatted "Date: ...\r\n" header string.
{#size-1}
size
const inline
inline size_t size() const
Returns the byte length of the formatted Date header string.
{#method}
Method
#include <icy/http/request.h>
HTTP request methods.
Public Static Attributes
| Return | Name | Description |
|---|---|---|
const std::string | Get static | |
const std::string | Head static | |
const std::string | Put static | |
const std::string | Post static | |
const std::string | Options static | |
const std::string | Delete static | |
const std::string | Trace static | |
const std::string | Connect static |
{#get-4}
Get
static
const std::string Get
{#head}
Head
static
const std::string Head
{#put}
Put
static
const std::string Put
{#post-2}
Post
static
const std::string Post
{#options-3}
Options
static
const std::string Options
{#delete}
Delete
static
const std::string Delete
{#trace}
Trace
static
const std::string Trace
{#connect-13}
Connect
static
const std::string Connect
{#ws}
ws
WebSocket framing, handshakes, and connection helpers.
Classes
| Name | Description |
|---|---|
ConnectionAdapter | WebSocket class which belongs to an HTTP connection. |
WebSocket | Standalone WebSocket class. |
WebSocketAdapter | WebSocket protocol adapter for both client and server endpoints. |
WebSocketException | |
WebSocketFramer | WebSocket frame encoder/decoder and handshake validator for RFC 6455. |
Enumerations
| Name | Description |
|---|---|
Mode | WebSocket endpoint mode. |
FrameFlags | Frame header flags. |
Opcode | Frame header opcodes. |
SendFlags | Combined header flags and opcodes for identifying the payload type of sent frames. |
CloseStatusCode | StatusCodes for CLOSE frames sent with shutdown(). |
ErrorCode | These error codes can be obtained from WebSocket exceptions to determine the exact cause of the error. |
CloseState |
{#mode-2}
Mode
enum Mode
WebSocket endpoint mode.
| Value | Description |
|---|---|
ServerSide | Server-side WebSocket. |
ClientSide | Client-side WebSocket. |
{#frameflags}
FrameFlags
enum FrameFlags
Frame header flags.
| Value | Description |
|---|---|
Fin | FIN bit: final fragment of a multi-fragment message. |
Rsv1 | Reserved for future use. Must be zero. |
Rsv2 | Reserved for future use. Must be zero. |
Rsv3 | Reserved for future use. Must be zero. |
{#opcode}
Opcode
enum Opcode
Frame header opcodes.
| Value | Description |
|---|---|
Continuation | Continuation frame. |
Text | Text frame. |
Binary | Binary frame. |
Close | Close connection. |
Ping | Ping frame. |
Pong | Pong frame. |
Bitmask | Bit mask for opcodes. |
{#sendflags}
SendFlags
enum SendFlags
Combined header flags and opcodes for identifying the payload type of sent frames.
| Value | Description |
|---|---|
Text | |
Binary |
{#closestatuscode}
CloseStatusCode
enum CloseStatusCode
StatusCodes for CLOSE frames sent with shutdown().
| Value | Description |
|---|---|
NormalClose | |
EndpointGoingAway | |
ProtocolError | |
PayloadNotAcceptable | |
Reserved | |
ReservedNoStatusCode | |
ReservedAbnormalClose | |
MalformedPayload | |
PolicyViolation | |
PayloadTooBig | |
ExtensionRequired | |
UnexpectedCondition | |
ReservedTLSFailure |
{#errorcode}
ErrorCode
enum ErrorCode
These error codes can be obtained from WebSocket exceptions to determine the exact cause of the error.
| Value | Description |
|---|---|
NoHandshake | No Connection: Upgrade or Upgrade: websocket header in handshake request. |
HandshakeNoVersion | No Sec-WebSocket-Version header in handshake request. |
HandshakeUnsupportedVersion | Unsupported WebSocket version requested by client. |
HandshakeNoKey | No Sec-WebSocket-Key header in handshake request. |
HandshakeAccept | No Sec-WebSocket-Accept header or wrong value. |
Unauthorized | The server rejected the username or password for authentication. |
PayloadTooBig | Payload too big for supplied buffer. |
IncompleteFrame | Incomplete frame received. |
InvalidRsvBits | RSV bits set without extension negotiation. |
InvalidOpcode | Unknown or reserved opcode received. |
UnmaskedClientFrame | Client-to-server frame not masked (RFC 6455 violation). |
ProtocolViolation | General RFC 6455 protocol violation. |
{#closestate}
CloseState
enum CloseState
| Value | Description |
|---|---|
Open | |
CloseSent | |
CloseReceived | |
Closed |
Variables
| Return | Name | Description |
|---|---|---|
constexpr auto | ServerSide static | |
constexpr auto | ClientSide static | |
constexpr char | ProtocolGuid | |
constexpr char | ProtocolVersion | The WebSocket protocol version supported (13). |
{#serverside}
ServerSide
static
constexpr auto ServerSide = Mode::ServerSide
{#clientside}
ClientSide
static
constexpr auto ClientSide = Mode::ClientSide
{#protocolguid}
ProtocolGuid
constexpr char ProtocolGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
{#protocolversion}
ProtocolVersion
constexpr char ProtocolVersion = "13"
The WebSocket protocol version supported (13).
{#connectionadapter-2}
ConnectionAdapter
#include <icy/http/websocket.h>
Inherits:
WebSocketAdapter
WebSocket class which belongs to an HTTP connection.
Public Methods
| Return | Name | Description |
|---|---|---|
ConnectionAdapter | Creates a ConnectionAdapter for upgrading an existing HTTP connection to WebSocket. Disables automatic header sending on the underlying connection. | |
void | onHandshakeComplete virtual | Called when the WebSocket handshake completes. Emits the connect event via the socket emitter chain. |
{#connectionadapter-3}
ConnectionAdapter
ConnectionAdapter(Connection * connection, ws::Mode mode)
Creates a ConnectionAdapter for upgrading an existing HTTP connection to WebSocket. Disables automatic header sending on the underlying connection.
Parameters
-
connectionThe HTTP connection to upgrade. -
modeServerSide or ClientSide.
{#onhandshakecomplete}
onHandshakeComplete
virtual
virtual void onHandshakeComplete()
Called when the WebSocket handshake completes. Emits the connect event via the socket emitter chain.
Protected Attributes
| Return | Name | Description |
|---|---|---|
Connection * | _connection |
{#_connection-3}
_connection
Connection * _connection
{#websocket}
WebSocket
#include <icy/http/websocket.h>
Inherits:
WebSocketAdapter
Standalone WebSocket class.
Public Methods
| Return | Name | Description |
|---|---|---|
WebSocket | Creates the WebSocket with the given Socket. The Socket should be a TCPSocket or a SSLSocket, depending on the protocol used (ws or wss). | |
http::Request & | request | Returns the HTTP request used during the WebSocket handshake. |
http::Response & | response | Returns the HTTP response received during the WebSocket handshake. |
{#websocket-1}
WebSocket
WebSocket(const net::Socket::Ptr & socket)
Creates the WebSocket with the given Socket. The Socket should be a TCPSocket or a SSLSocket, depending on the protocol used (ws or wss).
{#request-11}
request
http::Request & request()
Returns the HTTP request used during the WebSocket handshake.
{#response-9}
response
http::Response & response()
Returns the HTTP response received during the WebSocket handshake.
Protected Attributes
| Return | Name | Description |
|---|---|---|
http::Request | _request | |
http::Response | _response |
{#_request-2}
_request
http::Request _request
{#_response-2}
_response
http::Response _response
Public Types
| Name | Description |
|---|---|
Vec |
{#vec-4}
Vec
std::vector< WebSocket > Vec()
{#websocketadapter}
WebSocketAdapter
#include <icy/http/websocket.h>
Inherits:
SocketEmitterSubclassed by:ConnectionAdapter,WebSocket
WebSocket protocol adapter for both client and server endpoints.
Public Attributes
| Return | Name | Description |
|---|---|---|
net::Socket::Ptr | socket | Pointer to the underlying socket. Sent data will be proxied to this socket. |
{#socket-6}
socket
net::Socket::Ptr socket
Pointer to the underlying socket. Sent data will be proxied to this socket.
Public Methods
| Return | Name | Description |
|---|---|---|
WebSocketAdapter | Creates a WebSocketAdapter using the given socket, mode and HTTP message objects. | |
ssize_t | send virtual | Frames and sends data to the peer's address. |
ssize_t | send virtual | Frames and sends data to a specific peer address (for UDP-backed sockets). |
ssize_t | sendOwned virtual | Sends an owned payload buffer to the connected peer. |
ssize_t | sendOwned virtual | |
bool | shutdown virtual | Sends a WebSocket CLOSE frame with the given status code and message, then closes the underlying socket. |
void | sendClientRequest virtual | Client side. |
void | handleClientResponse virtual | Parses the server's HTTP upgrade response and completes the handshake. Any data remaining in the buffer after the HTTP response is re-fed as WebSocket frames. |
void | handleServerRequest virtual | Server side. |
void | onHandshakeComplete virtual | Called when the WebSocket handshake completes. Emits the connect event to downstream handlers. |
{#websocketadapter-1}
WebSocketAdapter
WebSocketAdapter(const net::Socket::Ptr & socket, ws::Mode mode, http::Request & request, http::Response & response)
Creates a WebSocketAdapter using the given socket, mode and HTTP message objects.
Parameters
-
socketThe underlying TCP or SSL socket. -
modeServerSide or ClientSide. -
requestHTTP request used for the handshake. -
responseHTTP response used for the handshake.
{#send-14}
send
virtual
virtual ssize_t send(const char * data, size_t len, int flags)
Frames and sends data to the peer's address.
Parameters
-
dataPointer to the payload. -
lenPayload length in bytes. -
flagsws::SendFlags::Text or ws::SendFlags::Binary.
Returns
Number of bytes sent, or -1 on error.
{#send-15}
send
virtual
virtual ssize_t send(const char * data, size_t len, const net::Address & peerAddr, int flags)
Frames and sends data to a specific peer address (for UDP-backed sockets).
Parameters
-
dataPointer to the payload. -
lenPayload length in bytes. -
peerAddrDestination address. -
flagsws::SendFlags::Text or ws::SendFlags::Binary.
Returns
Number of bytes sent, or -1 on error.
{#sendowned-12}
sendOwned
virtual
virtual ssize_t sendOwned(Buffer && buffer, int flags)
Sends an owned payload buffer to the connected peer.
The buffer is moved through the adapter chain and retained by the transport layer until async write completion.
{#sendowned-13}
sendOwned
virtual
virtual ssize_t sendOwned(Buffer && buffer, const net::Address & peerAddr, int flags)
{#shutdown-8}
shutdown
virtual
virtual bool shutdown(uint16_t statusCode, const std::string & statusMessage)
Sends a WebSocket CLOSE frame with the given status code and message, then closes the underlying socket.
Parameters
-
statusCodeWebSocket close status code (e.g. 1000 for normal close). -
statusMessageHuman-readable reason for closing.
Returns
true if the close frame was sent successfully.
{#sendclientrequest}
sendClientRequest
virtual
virtual void sendClientRequest()
Client side.
Sends the WebSocket HTTP upgrade request to initiate the handshake. Called automatically on socket connect.
{#handleclientresponse}
handleClientResponse
virtual
virtual void handleClientResponse(const MutableBuffer & buffer, const net::Address & peerAddr)
Parses the server's HTTP upgrade response and completes the handshake. Any data remaining in the buffer after the HTTP response is re-fed as WebSocket frames.
Parameters
-
bufferBuffer containing the server's HTTP response. -
peerAddrAddress of the peer.
{#handleserverrequest}
handleServerRequest
virtual
virtual void handleServerRequest(const MutableBuffer & buffer, const net::Address & peerAddr)
Server side.
Parses the client's HTTP upgrade request and sends the 101 response.
Parameters
-
bufferBuffer containing the client's HTTP upgrade request. -
peerAddrAddress of the peer.
{#onhandshakecomplete-1}
onHandshakeComplete
virtual
virtual void onHandshakeComplete()
Called when the WebSocket handshake completes. Emits the connect event to downstream handlers.
Protected Attributes
| Return | Name | Description |
|---|---|---|
WebSocketFramer | framer | |
http::Request & | _request | |
http::Response & | _response | |
ws::CloseState | _closeState |
{#framer}
framer
WebSocketFramer framer
{#_request-3}
_request
http::Request & _request
{#_response-3}
_response
http::Response & _response
{#_closestate}
_closeState
ws::CloseState _closeState {}
Protected Methods
| Return | Name | Description |
|---|---|---|
bool | sendControlFrame | |
void | resetFrameState |
{#sendcontrolframe}
sendControlFrame
bool sendControlFrame(ws::Opcode opcode, const char * payload, size_t payloadLen, const net::Address & peerAddr)
{#resetframestate}
resetFrameState
void resetFrameState()
Private Methods
| Return | Name | Description |
|---|---|---|
bool | onSocketConnect virtual | Called by the socket on connect; initiates the client handshake. |
bool | onSocketRecv virtual | Called by the socket on each received buffer; handles handshake or frame parsing depending on state. |
bool | onSocketClose virtual | Called by the socket on close; resets framer state. |
{#onsocketconnect-4}
onSocketConnect
virtual
virtual bool onSocketConnect(net::Socket & socket)
Called by the socket on connect; initiates the client handshake.
{#onsocketrecv-6}
onSocketRecv
virtual
virtual bool onSocketRecv(net::Socket & socket, const MutableBuffer & buffer, const net::Address & peerAddress)
Called by the socket on each received buffer; handles handshake or frame parsing depending on state.
{#onsocketclose-4}
onSocketClose
virtual
virtual bool onSocketClose(net::Socket & socket)
Called by the socket on close; resets framer state.
{#websocketexception}
WebSocketException
#include <icy/http/websocket.h>
Inherits:
runtime_error
Public Methods
| Return | Name | Description |
|---|---|---|
WebSocketException inline | ||
ErrorCode | code const inline | |
bool | hasCloseStatus const inline | |
uint16_t | closeStatus const inline |
{#websocketexception-1}
WebSocketException
inline
inline WebSocketException(ErrorCode code, std::string message, uint16_t closeStatus)
{#code}
code
const inline
inline ErrorCode code() const
{#hasclosestatus}
hasCloseStatus
const inline
inline bool hasCloseStatus() const
{#closestatus}
closeStatus
const inline
inline uint16_t closeStatus() const
Private Attributes
| Return | Name | Description |
|---|---|---|
ErrorCode | _code | |
uint16_t | _closeStatus |
{#_code}
_code
ErrorCode _code
{#_closestatus}
_closeStatus
uint16_t _closeStatus
{#websocketframer}
WebSocketFramer
#include <icy/http/websocket.h>
WebSocket frame encoder/decoder and handshake validator for RFC 6455.
Public Methods
| Return | Name | Description |
|---|---|---|
WebSocketFramer | Creates a WebSocketFramer operating in the given endpoint mode. Client-side framers mask outgoing payloads; server-side framers do not. | |
size_t | writeFrame virtual | Encodes data into a WebSocket frame and writes it to frame. |
uint64_t | readFrame virtual | Decodes a single WebSocket frame from frame. |
bool | handshakeComplete const | Returns true if the WebSocket handshake has completed successfully. |
void | acceptServerRequest | Server side. |
void | createClientHandshakeRequest | Client side. |
bool | checkClientHandshakeResponse | Validates the server's 101 Switching Protocols response. |
void | completeClientHandshake | Completes the client-side handshake by verifying Connection, Upgrade and Sec-WebSocket-Accept headers. Advances internal state to "complete". |
{#websocketframer-1}
WebSocketFramer
WebSocketFramer(ws::Mode mode)
Creates a WebSocketFramer operating in the given endpoint mode. Client-side framers mask outgoing payloads; server-side framers do not.
Parameters
modeServerSide or ClientSide.
{#writeframe}
writeFrame
virtual
virtual size_t writeFrame(const char * data, size_t len, int flags, BitWriter & frame)
Encodes data into a WebSocket frame and writes it to frame.
Parameters
-
dataPointer to the payload data. -
lenPayload length in bytes. -
flagsFrame flags: ws::SendFlags::Text, ws::SendFlags::Binary, or a control frame opcode combined with FrameFlags::Fin. -
frameBitWriter to write the encoded frame into.
Returns
Total number of bytes written to the frame buffer (header + payload).
{#readframe}
readFrame
virtual
virtual uint64_t readFrame(BitReader & frame, char *& payload)
Decodes a single WebSocket frame from frame.
The payload is unmasked in-place in the source buffer; no copy is made. payload is set to point at the start of the payload within frame's buffer.
Parameters
-
frameBitReader positioned at the start of a frame. -
payloadSet to point at the start of the decoded payload. Not null-terminated.
Returns
Payload length in bytes.
Exceptions
std::runtime_erroron protocol violations or if the buffer is too small.
{#handshakecomplete}
handshakeComplete
const
bool handshakeComplete() const
Returns true if the WebSocket handshake has completed successfully.
{#acceptserverrequest}
acceptServerRequest
void acceptServerRequest(http::Request & request, http::Response & response)
Server side.
Validates the client upgrade request and writes a 101 Switching Protocols response. Sets the internal state to mark the handshake as complete.
Parameters
-
requestIncoming HTTP upgrade request. -
responseHTTP response to populate with the handshake reply.
Exceptions
std::runtime_errorif the request is not a valid WebSocket upgrade.
{#createclienthandshakerequest}
createClientHandshakeRequest
void createClientHandshakeRequest(http::Request & request)
Client side.
Populates request with the WebSocket upgrade headers (Connection, Upgrade, Sec-WebSocket-Key, Sec-WebSocket-Version) to initiate the handshake.
Parameters
requestHTTP request to add upgrade headers to.
{#checkclienthandshakeresponse}
checkClientHandshakeResponse
bool checkClientHandshakeResponse(http::Response & response)
Validates the server's 101 Switching Protocols response.
Parameters
responseThe HTTP response received from the server.
Returns
true if the handshake succeeded and data can flow.
Exceptions
std::runtime_errorif the server rejected or mishandled the upgrade.
{#completeclienthandshake}
completeClientHandshake
void completeClientHandshake(http::Response & response)
Completes the client-side handshake by verifying Connection, Upgrade and Sec-WebSocket-Accept headers. Advances internal state to "complete".
Parameters
responseThe 101 Switching Protocols response from the server.
Exceptions
std::runtime_errorif any required header is missing or incorrect.
Protected Methods
| Return | Name | Description |
|---|---|---|
int | frameFlags const | Returns the frame flags of the most recently received frame. Set by readFrame() |
bool | mustMaskPayload const | Returns true if the payload must be masked. Used by writeFrame() |
ws::Mode | mode const |
{#frameflags-1}
frameFlags
const
int frameFlags() const
Returns the frame flags of the most recently received frame. Set by readFrame()
{#mustmaskpayload}
mustMaskPayload
const
bool mustMaskPayload() const
Returns true if the payload must be masked. Used by writeFrame()
{#mode-3}
mode
const
ws::Mode mode() const
Private Attributes
| Return | Name | Description |
|---|---|---|
ws::Mode | _mode | |
int | _frameFlags | |
int | _headerState | |
bool | _maskPayload | |
Random | _rnd | |
std::string | _key | |
bool | _fragmented | Currently receiving a fragmented message. |
int | _fragmentOpcode | Opcode of the first frame in the fragment sequence. |
Buffer | _fragmentBuffer | Accumulated payload from continuation frames. |
Buffer | _incompleteFrame | Buffer for incomplete frame data across TCP segments. |
{#_mode-3}
_mode
ws::Mode _mode
{#_frameflags}
_frameFlags
int _frameFlags
{#_headerstate}
_headerState
int _headerState
{#_maskpayload}
_maskPayload
bool _maskPayload
{#_rnd}
_rnd
Random _rnd
{#_key}
_key
std::string _key
{#_fragmented}
_fragmented
bool _fragmented {false}
Currently receiving a fragmented message.
{#_fragmentopcode}
_fragmentOpcode
int _fragmentOpcode {0}
Opcode of the first frame in the fragment sequence.
{#_fragmentbuffer}
_fragmentBuffer
Buffer _fragmentBuffer
Accumulated payload from continuation frames.
{#_incompleteframe}
_incompleteFrame
Buffer _incompleteFrame
Buffer for incomplete frame data across TCP segments.