![]() |
jsocketpp 1.0
A cross-platform C++20 socket library.
|
Classes and functions for TCP networking. More...

Classes | |
| class | jsocketpp::ServerSocket |
| TCP server socket abstraction for cross-platform C++ networking. More... | |
| class | jsocketpp::Socket |
| TCP client connection abstraction (Java-like interface). More... | |
Functions | |
| jsocketpp::ServerSocket::ServerSocket ()=delete | |
| Default constructor (deleted) for ServerSocket class. | |
| jsocketpp::ServerSocket::ServerSocket (Port port, std::string_view localAddress={}, bool autoBindListen=true, bool reuseAddress=true, int soTimeoutMillis=-1, bool dualStack=true) | |
| Constructs a ServerSocket for listening to incoming TCP connections with full configuration control. | |
| Port | jsocketpp::ServerSocket::getLocalPort () const |
| Retrieve the local port number to which the server socket is bound. | |
| std::string | jsocketpp::ServerSocket::getLocalSocketAddress () const |
| Get the local socket address (IP and port) to which the server socket is bound. | |
| jsocketpp::ServerSocket::ServerSocket (const ServerSocket &rhs)=delete | |
| Copy constructor (deleted). | |
| ServerSocket & | jsocketpp::ServerSocket::operator= (const ServerSocket &rhs)=delete |
| Copy assignment operator (deleted). | |
| jsocketpp::ServerSocket::ServerSocket (ServerSocket &&rhs) noexcept | |
| Move constructor that transfers ownership of server socket resources. | |
| ServerSocket & | jsocketpp::ServerSocket::operator= (ServerSocket &&rhs) noexcept |
| Move assignment operator for ServerSocket. | |
| jsocketpp::ServerSocket::~ServerSocket () noexcept override | |
| Destructor that automatically closes the server socket and releases all associated resources. | |
| void | jsocketpp::ServerSocket::bind () |
| Binds the server socket to the configured port and network interface. | |
| bool | jsocketpp::ServerSocket::isBound () const noexcept |
| Check if the server socket is bound to a local address. | |
| void | jsocketpp::ServerSocket::listen (int backlog=128) |
| Marks the socket as a passive (listening) socket, ready to accept incoming TCP connection requests. | |
| bool | jsocketpp::ServerSocket::isListening () const noexcept |
| Check if the server socket is currently listening for incoming connections. | |
| Socket | jsocketpp::ServerSocket::accept (std::optional< std::size_t > recvBufferSize=std::nullopt, std::optional< std::size_t > sendBufferSize=std::nullopt, std::optional< std::size_t > internalBufferSize=std::nullopt, int soRecvTimeoutMillis=-1, int soSendTimeoutMillis=-1, bool tcpNoDelay=true, bool keepAlive=false, bool nonBlocking=false) const |
| Accept an incoming client connection, respecting the configured socket timeout and applying tuning options. | |
| Socket | jsocketpp::ServerSocket::accept (int timeoutMillis, std::optional< std::size_t > recvBufferSize=std::nullopt, std::optional< std::size_t > sendBufferSize=std::nullopt, std::optional< std::size_t > internalBufferSize=std::nullopt, int soRecvTimeoutMillis=-1, int soSendTimeoutMillis=-1, bool tcpNoDelay=true, bool keepAlive=false, bool nonBlocking=false) const |
| Accept an incoming client connection, waiting up to the specified timeout and applying socket tuning options. | |
| std::optional< Socket > | jsocketpp::ServerSocket::tryAccept (std::optional< std::size_t > recvBufferSize=std::nullopt, std::optional< std::size_t > sendBufferSize=std::nullopt, std::optional< std::size_t > internalBufferSize=std::nullopt, int soRecvTimeoutMillis=-1, int soSendTimeoutMillis=-1, bool tcpNoDelay=true, bool keepAlive=false, bool nonBlocking=false) const |
| Attempt to accept an incoming client connection, returning std::nullopt on timeout instead of throwing. | |
| std::optional< Socket > | jsocketpp::ServerSocket::tryAccept (int timeoutMillis, std::optional< std::size_t > recvBufferSize=std::nullopt, std::optional< std::size_t > sendBufferSize=std::nullopt, std::optional< std::size_t > internalBufferSize=std::nullopt, int soRecvTimeoutMillis=-1, int soSendTimeoutMillis=-1, bool tcpNoDelay=true, bool keepAlive=false, bool nonBlocking=false) const |
| Attempt to accept an incoming client connection, waiting up to a specified timeout and returning std::nullopt on timeout. | |
| Socket | jsocketpp::ServerSocket::acceptBlocking (std::optional< std::size_t > recvBufferSize=std::nullopt, std::optional< std::size_t > sendBufferSize=std::nullopt, std::optional< std::size_t > internalBufferSize=std::nullopt, int soRecvTimeoutMillis=-1, int soSendTimeoutMillis=-1, bool tcpNoDelay=true, bool keepAlive=false, bool nonBlocking=false) const |
| Accepts a TCP client connection, configures the socket, and returns a high-level Socket object. | |
| std::optional< Socket > | jsocketpp::ServerSocket::acceptNonBlocking (std::optional< std::size_t > recvBufferSize=std::nullopt, std::optional< std::size_t > sendBufferSize=std::nullopt, std::optional< std::size_t > internalBufferSize=std::nullopt, int soRecvTimeoutMillis=-1, int soSendTimeoutMillis=-1, bool tcpNoDelay=true, bool keepAlive=false, bool nonBlocking=false) const |
| Attempts to accept a client connection in non-blocking mode and returns a fully configured Socket. | |
| std::future< Socket > | jsocketpp::ServerSocket::acceptAsync (std::optional< std::size_t > recvBufferSize=std::nullopt, std::optional< std::size_t > sendBufferSize=std::nullopt, std::optional< std::size_t > internalBufferSize=std::nullopt, int soRecvTimeoutMillis=-1, int soSendTimeoutMillis=-1, bool tcpNoDelay=true, bool keepAlive=false, bool nonBlocking=false) const |
| Asynchronously accept an incoming client connection, returning a std::future that resolves to a configured Socket. | |
| void | jsocketpp::ServerSocket::acceptAsync (std::function< void(std::optional< Socket >, std::exception_ptr)> callback, std::optional< std::size_t > recvBufferSize=std::nullopt, std::optional< std::size_t > sendBufferSize=std::nullopt, std::optional< std::size_t > internalBufferSize=std::nullopt, int soRecvTimeoutMillis=-1, int soSendTimeoutMillis=-1, bool tcpNoDelay=true, bool keepAlive=false, bool nonBlocking=false) const |
| Asynchronously accept a client connection and invoke a callback upon completion or error. | |
| void | jsocketpp::ServerSocket::close () |
| Closes the server socket and releases its associated system resources. | |
| bool | jsocketpp::ServerSocket::isValid () const noexcept |
| Check whether the server socket is currently open and valid. | |
| bool | jsocketpp::ServerSocket::isClosed () const noexcept |
| Check if the server socket has been closed. | |
| bool | jsocketpp::ServerSocket::waitReady (std::optional< int > timeoutMillis=std::nullopt) const |
| Waits for the server socket to become ready to accept an incoming connection. | |
| void | jsocketpp::ServerSocket::setDefaultReceiveBufferSize (const std::size_t size) |
| Set the default receive buffer size for accepted client sockets. | |
| std::size_t | jsocketpp::ServerSocket::getDefaultReceiveBufferSize () const noexcept |
| Get the current default receive buffer size for accepted client sockets. | |
| void | jsocketpp::ServerSocket::setDefaultSendBufferSize (const std::size_t size) |
| Set the default send buffer size for accepted client sockets. | |
| std::size_t | jsocketpp::ServerSocket::getDefaultSendBufferSize () const noexcept |
| Get the current default send buffer size for accepted client sockets. | |
| void | jsocketpp::ServerSocket::setDefaultInternalBufferSize (const std::size_t size) |
| Set the per-instance default internal buffer size used for buffered read operations. | |
| std::size_t | jsocketpp::ServerSocket::getDefaultInternalBufferSize () const noexcept |
| Get the per-instance default internal buffer size used for buffered read operations. | |
| void | jsocketpp::ServerSocket::cleanup () |
| Cleans up internal resources and resets the server socket state. | |
| void | jsocketpp::ServerSocket::cleanupAndThrow (int errorCode) |
| Cleans up internal resources and throws a SocketException. | |
| void | jsocketpp::ServerSocket::cleanupAndRethrow () |
| Cleans up internal resources and rethrows the current exception. | |
| std::size_t | jsocketpp::ServerSocket::getEffectiveReceiveBufferSize (const std::optional< std::size_t > recvBufferSize) const |
| Get the effective receive buffer size to use for socket read operations. | |
| std::size_t | jsocketpp::ServerSocket::getEffectiveSendBufferSize (std::optional< std::size_t > sendBufferSize) const |
| Get the effective send buffer size to use for socket write operations. | |
| std::size_t | jsocketpp::ServerSocket::getEffectiveInternalBufferSize (const std::optional< std::size_t > internalBufferSize) const |
| Get the effective internal buffer size to use for buffered socket read operations. | |
| std::tuple< std::size_t, std::size_t, std::size_t > | jsocketpp::ServerSocket::resolveBuffers (const std::optional< std::size_t > recv, const std::optional< std::size_t > send, const std::optional< std::size_t > internal) const |
| Resolves effective receive and send buffer sizes from optional user inputs. | |
| jsocketpp::Socket::Socket (SOCKET client, const sockaddr_storage &addr, socklen_t len, std::size_t recvBufferSize=DefaultBufferSize, std::size_t sendBufferSize=DefaultBufferSize, std::size_t internalBufferSize=DefaultBufferSize, int soRecvTimeoutMillis=-1, int soSendTimeoutMillis=-1, bool tcpNoDelay=true, bool keepAlive=false, bool nonBlocking=false) | |
| Wraps an accepted TCP client socket with optional tuning parameters. | |
| jsocketpp::Socket::Socket ()=delete | |
| Default constructor (deleted) for Socket class. | |
| jsocketpp::Socket::Socket (std::string_view host, Port port, std::optional< std::size_t > recvBufferSize=std::nullopt, std::optional< std::size_t > sendBufferSize=std::nullopt, std::optional< std::size_t > internalBufferSize=std::nullopt, bool reuseAddress=true, int soRecvTimeoutMillis=-1, int soSendTimeoutMillis=-1, bool dualStack=true, bool tcpNoDelay=true, bool keepAlive=false, bool nonBlocking=false, bool autoConnect=true, bool autoBind=false, std::string_view localAddress="", Port localPort=0) | |
| Constructs a TCP client socket, resolves the remote host and port, and optionally binds or connects. | |
| jsocketpp::Socket::Socket (const Socket &rhs)=delete | |
| Copy constructor (deleted) for Socket class. | |
| jsocketpp::Socket::Socket (Socket &&rhs) noexcept | |
| Move constructor that transfers ownership of socket resources. | |
| Socket & | jsocketpp::Socket::operator= (const Socket &rhs)=delete |
| Copy assignment operator (deleted) for Socket class. | |
| Socket & | jsocketpp::Socket::operator= (Socket &&rhs) noexcept |
| Move assignment operator that transfers socket ownership safely. | |
| jsocketpp::Socket::~Socket () noexcept override | |
| Destructs the Socket object, closing connections and freeing resources. | |
| void | jsocketpp::Socket::bind (std::string_view localHost, Port port) |
| Binds the client socket to a specific local IP address and/or port. | |
| void | jsocketpp::Socket::bind (Port port) |
| Binds the client socket to all interfaces (INADDR_ANY) using the specified port. | |
| void | jsocketpp::Socket::bind () |
| Binds the client socket to all interfaces using an ephemeral port. | |
| bool | jsocketpp::Socket::isBound () const noexcept |
| Indicates whether the socket has been explicitly bound to a local address and/or port. | |
| bool | jsocketpp::Socket::isConnected () const noexcept |
| Indicates whether the socket has been successfully connected to a remote host. | |
| std::string | jsocketpp::Socket::getLocalIp (bool convertIPv4Mapped=true) const |
| Retrieves the local IP address this socket is bound to. | |
| Port | jsocketpp::Socket::getLocalPort () const |
| Retrieves the local port number this socket is bound to. | |
| std::string | jsocketpp::Socket::getLocalSocketAddress (bool convertIPv4Mapped=true) const |
| Retrieves the full local socket address in the form "IP:port". | |
| std::string | jsocketpp::Socket::getRemoteIp (bool convertIPv4Mapped=true) const |
| Retrieves the IP address of the remote peer this TCP socket is connected to. | |
| Port | jsocketpp::Socket::getRemotePort () const |
| Retrieves the port number of the remote peer this TCP socket is connected to. | |
| std::string | jsocketpp::Socket::getRemoteSocketAddress (bool convertIPv4Mapped=true) const |
| Get the connected peer's socket address as a formatted string. | |
| void | jsocketpp::Socket::connect (int timeoutMillis=-1) |
| Establishes a TCP connection to the remote host with optional timeout control. | |
| template<typename T> | |
| T | jsocketpp::Socket::read () |
| Reads a fixed-size, trivially copyable object of type T from the socket. | |
| std::string | jsocketpp::Socket::readExact (std::size_t n) const |
| Reads exactly n bytes from the socket into a std::string. | |
| std::string | jsocketpp::Socket::readUntil (char delimiter, std::size_t maxLen=8192, bool includeDelimiter=true) |
| Reads data from the socket until a specified delimiter character is encountered. | |
| std::string | jsocketpp::Socket::readLine (const std::size_t maxLen=8192, const bool includeDelimiter=true) |
| Reads a line terminated by ' ' from the socket. | |
| std::string | jsocketpp::Socket::readAtMost (std::size_t n) const |
| Performs a single best-effort read of up to n bytes from the socket. | |
| std::size_t | jsocketpp::Socket::readInto (void *buffer, const std::size_t len) const |
| Reads available data from the socket into the provided buffer. | |
| std::size_t | jsocketpp::Socket::readIntoExact (void *buffer, const std::size_t len) const |
| Reads exactly len bytes into the given buffer (looped recv). | |
| std::string | jsocketpp::Socket::readAtMostWithTimeout (std::size_t n, int timeoutMillis) const |
| Attempts a best-effort read of up to n bytes with a timeout constraint. | |
| template<typename T> | |
| std::string | jsocketpp::Socket::readPrefixed () |
| Reads a length-prefixed payload using a fixed-size prefix type. | |
| template<typename T> | |
| std::string | jsocketpp::Socket::readPrefixed (const std::size_t maxPayloadLen) |
| Reads a length-prefixed message with an upper bound check. | |
| std::string | jsocketpp::Socket::readAvailable () const |
| Reads all bytes currently available on the socket without blocking. | |
| std::size_t | jsocketpp::Socket::readIntoAvailable (void *buffer, std::size_t bufferSize) const |
| Reads all currently available bytes into the provided buffer without blocking. | |
| std::size_t | jsocketpp::Socket::readv (std::span< BufferView > buffers) const |
| Performs a vectorized read into multiple buffers using a single system call. | |
| std::size_t | jsocketpp::Socket::readvAll (std::span< BufferView > buffers) const |
| Reads exactly the full contents of all provided buffers. | |
| std::size_t | jsocketpp::Socket::readvAllWithTotalTimeout (std::span< BufferView > buffers, int timeoutMillis) const |
| Reads exactly the full contents of all buffers within a timeout. | |
| std::size_t | jsocketpp::Socket::readvAtMostWithTimeout (std::span< BufferView > buffers, int timeoutMillis) const |
| Attempts a single vectorized read into multiple buffers with a timeout. | |
| std::string | jsocketpp::Socket::peek (std::size_t n) const |
| Peeks at incoming data without consuming it. | |
| void | jsocketpp::Socket::discard (std::size_t n, std::size_t chunkSize=1024) const |
| Discards exactly n bytes from the socket by reading and discarding them. | |
| void | jsocketpp::Socket::close () |
| Closes the socket connection and releases associated resources. | |
| void | jsocketpp::Socket::shutdown (ShutdownMode how) const |
| Shutdown specific communication aspects of the socket. | |
| std::size_t | jsocketpp::Socket::write (std::string_view message) const |
| Sends data to the socket using a single, best-effort write operation. | |
| std::size_t | jsocketpp::Socket::writeAll (std::string_view message) const |
| Writes the entire contents of a message to the socket, retrying as needed. | |
| template<typename T> | |
| std::size_t | jsocketpp::Socket::writePrefixed (const std::string_view payload) |
| Writes a length-prefixed payload using a fixed-size integral prefix. | |
| template<typename T> | |
| std::size_t | jsocketpp::Socket::writePrefixed (const void *data, std::size_t len) const |
| Writes a binary payload prefixed with its length using a fixed-size integer type. | |
| std::size_t | jsocketpp::Socket::writev (std::span< const std::string_view > buffers) const |
| Writes multiple buffers in a single system call using scatter/gather I/O. | |
| std::size_t | jsocketpp::Socket::writevAll (std::span< const std::string_view > buffers) const |
| Writes all buffers fully using vectorized I/O with automatic retry on partial sends. | |
| std::size_t | jsocketpp::Socket::writeAtMostWithTimeout (std::string_view data, int timeoutMillis) const |
| Performs a best-effort write with a total timeout. | |
| std::size_t | jsocketpp::Socket::writeFrom (const void *data, std::size_t len) const |
| Writes up to len bytes from a raw memory buffer in a single send call. | |
| std::size_t | jsocketpp::Socket::writeFromAll (const void *data, std::size_t len) const |
| Writes all bytes from a raw memory buffer, retrying until complete. | |
| std::size_t | jsocketpp::Socket::writeWithTotalTimeout (std::string_view data, int timeoutMillis) const |
| Writes the full payload with a total timeout across all retries. | |
| std::size_t | jsocketpp::Socket::writevWithTotalTimeout (std::span< const std::string_view > buffers, int timeoutMillis) const |
| Writes all buffers fully within a total timeout using vectorized I/O. | |
| std::size_t | jsocketpp::Socket::writevFrom (std::span< const BufferView > buffers) const |
| Writes multiple raw memory regions using vectorized I/O. | |
| std::size_t | jsocketpp::Socket::writevFromAll (std::span< BufferView > buffers) const |
| Writes all raw memory regions fully using scatter/gather I/O. | |
| std::size_t | jsocketpp::Socket::writevFromWithTotalTimeout (std::span< BufferView > buffers, int timeoutMillis) const |
| Writes all raw memory buffers fully within a timeout using scatter I/O. | |
| void | jsocketpp::Socket::setInternalBufferSize (std::size_t newLen) |
| Sets the size of the internal read buffer used for string operations. | |
| bool | jsocketpp::Socket::isValid () const noexcept |
| Check if the socket is valid and open for communication. | |
| bool | jsocketpp::Socket::waitReady (bool forWrite, int timeoutMillis) const |
| Waits for the socket to become ready for reading or writing. | |
| bool | jsocketpp::Socket::isClosed () const noexcept |
| Reports whether the socket has been closed or invalidated. | |
| bool | jsocketpp::Socket::isInputShutdown () const noexcept |
| Checks whether the socket's input stream has been shutdown. | |
| bool | jsocketpp::Socket::isOutputShutdown () const noexcept |
| Checks whether the socket's output stream has been shutdown. | |
| std::size_t | jsocketpp::Socket::readIntoInternal (void *buffer, std::size_t len, bool exact=false) const |
| Reads data from the socket into a user-supplied buffer. | |
| void | jsocketpp::Socket::cleanup () |
| Internal helper that closes the socket and clears address resolution state. | |
| void | jsocketpp::Socket::cleanupAndThrow (int errorCode) |
| Closes the socket, resets internal state, and throws a SocketException. | |
| void | jsocketpp::Socket::cleanupAndRethrow () |
| Cleans up socket resources and rethrows the currently active exception. | |
| void | jsocketpp::Socket::resetShutdownFlags () noexcept |
| Resets internal shutdown state flags to false. | |
| template<> | |
| std::string | jsocketpp::Socket::read () |
| Specialization of read<T>() for reading a single buffer of string data. | |
Friends | |
| class | jsocketpp::Socket::ServerSocket |
| Grants ServerSocket access to private members. | |
Classes and functions for TCP networking.
|
nodiscard |
Accept an incoming client connection, waiting up to the specified timeout and applying socket tuning options.
This method waits for a client connection using the specified timeout (in milliseconds), then calls the underlying system accept() and returns a fully configured Socket object.
Internally, this method uses waitReady(timeoutMillis) (based on select()) to wait for readiness and then calls acceptBlocking() with the resolved parameters.
The returned Socket will be configured with the following tuning options:
This method is not thread-safe. Concurrent calls to accept(), acceptBlocking(), or acceptNonBlocking() from multiple threads or processes may lead to race conditions. Synchronize access to the ServerSocket if needed.
| [in] | timeoutMillis | Timeout in milliseconds to wait for a connection:
|
| [in] | recvBufferSize | Optional socket receive buffer size (SO_RCVBUF) |
| [in] | sendBufferSize | Optional socket send buffer size (SO_SNDBUF) |
| [in] | internalBufferSize | Internal buffer used by read() and read<T>() |
| [in] | soRecvTimeoutMillis | Receive timeout in milliseconds (SO_RCVTIMEO); -1 disables |
| [in] | soSendTimeoutMillis | Send timeout in milliseconds (SO_SNDTIMEO); -1 disables |
| [in] | tcpNoDelay | Whether to disable Nagle’s algorithm (TCP_NODELAY); default: true |
| [in] | keepAlive | Whether to enable TCP keep-alive (SO_KEEPALIVE) |
| [in] | nonBlocking | Whether to set the accepted socket to non-blocking mode |
| SocketException | If:
|
| SocketTimeoutException | If no client connects before the timeout expires |
|
nodiscard |
Accept an incoming client connection, respecting the configured socket timeout and applying tuning options.
This method waits for an incoming connection using the timeout set via setSoTimeout() or getSoTimeout(). Once a connection is ready, it calls the underlying system accept() and returns a fully configured Socket object with the specified buffer sizes, timeouts, and TCP socket options.
Internally, this method uses select() via waitReady() to wait for readiness, then invokes accept(). The socket’s blocking mode (via setNonBlocking()) does not affect this method.
The returned Socket is configured immediately using the provided tuning parameters:
This method is not thread-safe. Concurrent calls to accept() or acceptNonBlocking() from multiple threads or processes may cause race conditions or undefined behavior. Protect the ServerSocket instance with a mutex if needed.
| [in] | recvBufferSize | Optional socket receive buffer size (SO_RCVBUF) |
| [in] | sendBufferSize | Optional socket send buffer size (SO_SNDBUF) |
| [in] | internalBufferSize | Optional internal buffer size for high-level reads |
| [in] | soRecvTimeoutMillis | Read timeout (SO_RCVTIMEO) in milliseconds; -1 disables |
| [in] | soSendTimeoutMillis | Send timeout (SO_SNDTIMEO) in milliseconds; -1 disables |
| [in] | tcpNoDelay | Whether to disable Nagle's algorithm (TCP_NODELAY); default: true |
| [in] | keepAlive | Whether to enable TCP keep-alive probes (SO_KEEPALIVE) |
| [in] | nonBlocking | Whether to set the accepted socket to non-blocking mode |
| SocketException | If: |
| SocketTimeoutException | If the timeout expires with no connection |
| void ServerSocket::acceptAsync | ( | std::function< void(std::optional< Socket >, std::exception_ptr)> | callback, |
| std::optional< std::size_t > | recvBufferSize = std::nullopt, | ||
| std::optional< std::size_t > | sendBufferSize = std::nullopt, | ||
| std::optional< std::size_t > | internalBufferSize = std::nullopt, | ||
| int | soRecvTimeoutMillis = -1, | ||
| int | soSendTimeoutMillis = -1, | ||
| bool | tcpNoDelay = true, | ||
| bool | keepAlive = false, | ||
| bool | nonBlocking = false ) const |
Asynchronously accept a client connection and invoke a callback upon completion or error.
This method starts a detached background thread that performs a socket accept() and invokes a user-provided callback upon completion. It is designed for event-driven or callback-oriented architectures where blocking or polling is not desirable.
This method is not thread-safe. Do not call accept(), acceptAsync(), or related methods concurrently on the same ServerSocket unless access is externally synchronized.
The ServerSocket must outlive the background thread and callback execution. Destroying the ServerSocket before the callback is invoked results in undefined behavior.
The Socket passed to the callback (if any) will be configured using:
| [in] | callback | Completion handler that receives the accepted socket or an exception |
| [in] | recvBufferSize | Optional receive buffer size (SO_RCVBUF) |
| [in] | sendBufferSize | Optional send buffer size (SO_SNDBUF) |
| [in] | internalBufferSize | Optional internal buffer for read<T>() |
| [in] | soRecvTimeoutMillis | Receive timeout (SO_RCVTIMEO) in milliseconds; -1 disables |
| [in] | soSendTimeoutMillis | Send timeout (SO_SNDTIMEO) in milliseconds; -1 disables |
| [in] | tcpNoDelay | Whether to disable Nagle’s algorithm (TCP_NODELAY); default: true |
| [in] | keepAlive | Whether to enable TCP keep-alive (SO_KEEPALIVE) |
| [in] | nonBlocking | Whether to immediately make the accepted socket non-blocking |
|
nodiscard |
Asynchronously accept an incoming client connection, returning a std::future that resolves to a configured Socket.
This method initiates an asynchronous accept operation on the server socket using std::async(std::launch::async, ...). It returns a std::future<Socket> that will become ready once a client is accepted or an error/timeout occurs.
This function is ideal for use in thread-based architectures where the server must continue operating while waiting for new clients in parallel.
This method is not thread-safe. You must externally synchronize calls to acceptAsync(), accept(), tryAccept(), and related methods on the same ServerSocket instance.
The ServerSocket object must remain valid and alive at least until the returned std::future has resolved and .get() has been called. Using this method in contexts where the ServerSocket may be destroyed early can lead to undefined behavior or dangling references.
The returned Socket (from .get()) will be initialized with:
| [in] | recvBufferSize | Optional socket receive buffer size (SO_RCVBUF) |
| [in] | sendBufferSize | Optional socket send buffer size (SO_SNDBUF) |
| [in] | internalBufferSize | Optional internal buffer size for read<T>() operations |
| [in] | soRecvTimeoutMillis | Socket receive timeout (SO_RCVTIMEO) in milliseconds; -1 disables |
| [in] | soSendTimeoutMillis | Socket send timeout (SO_SNDTIMEO) in milliseconds; -1 disables |
| [in] | tcpNoDelay | Whether to disable Nagle’s algorithm (TCP_NODELAY); default: true |
| [in] | keepAlive | Whether to enable TCP keep-alive (SO_KEEPALIVE) |
| [in] | nonBlocking | Whether to immediately set the accepted socket to non-blocking mode |
| SocketException | If a fatal socket error occurs during background accept |
| SocketTimeoutException | If no client connects and the configured timeout expires |
|
nodiscard |
Accepts a TCP client connection, configures the socket, and returns a high-level Socket object.
This method calls the underlying system accept() on the listening server socket.
This method is not thread-safe. Simultaneous accept() calls on the same ServerSocket from multiple threads may result in race conditions or inconsistent results.
| [in] | recvBufferSize | Optional socket receive buffer size (SO_RCVBUF) |
| [in] | sendBufferSize | Optional socket send buffer size (SO_SNDBUF) |
| [in] | internalBufferSize | Internal buffer used by read<T>() and read<std::string>() |
| [in] | soRecvTimeoutMillis | Receive timeout (SO_RCVTIMEO) in milliseconds; -1 disables |
| [in] | soSendTimeoutMillis | Send timeout (SO_SNDTIMEO) in milliseconds; -1 disables |
| [in] | tcpNoDelay | Whether to disable Nagle’s algorithm (TCP_NODELAY) |
| [in] | keepAlive | Whether to enable TCP keep-alive (SO_KEEPALIVE) |
| [in] | nonBlocking | Whether to immediately make the accepted socket non-blocking |
| SocketException | If: |
|
nodiscard |
Attempts to accept a client connection in non-blocking mode and returns a fully configured Socket.
This method calls the system accept() in non-blocking mode to check for pending client connections:
If a client is accepted, the returned Socket will be configured using the following options:
| [in] | recvBufferSize | Optional socket receive buffer size (SO_RCVBUF) |
| [in] | sendBufferSize | Optional socket send buffer size (SO_SNDBUF) |
| [in] | internalBufferSize | Internal buffer size for read<T>() |
| [in] | soRecvTimeoutMillis | Read timeout in milliseconds (SO_RCVTIMEO); -1 disables |
| [in] | soSendTimeoutMillis | Send timeout in milliseconds (SO_SNDTIMEO); -1 disables |
| [in] | tcpNoDelay | Disables Nagle's algorithm (TCP_NODELAY) if true (default: true) |
| [in] | keepAlive | Enables TCP keep-alive probes (SO_KEEPALIVE) if true |
| [in] | nonBlocking | Sets the accepted socket to non-blocking mode if true |
| SocketException | if:
|
| void ServerSocket::bind | ( | ) |
Binds the server socket to the configured port and network interface.
This method assigns a local address and port number to the socket, making it ready to accept incoming TCP connections.
| SocketException | if the bind operation fails (for example, if the port is already in use or insufficient permissions). |
| void Socket::bind | ( | ) |
Binds the client socket to all interfaces using an ephemeral port.
This overload delegates to the default configuration — bind to any interface, with any available port. Equivalent to calling bind("", 0).
| SocketException | if binding fails or the socket is already bound. |
| void Socket::bind | ( | Port | port | ) |
Binds the client socket to all interfaces (INADDR_ANY) using the specified port.
This overload binds to all available network interfaces using a specific local port. Equivalent to calling bind("", port).
| [in] | port | Port number to bind to. |
| SocketException | if binding fails or the socket is already bound. |
| void Socket::bind | ( | std::string_view | localHost, |
| Port | port ) |
Binds the client socket to a specific local IP address and/or port.
This method provides fine-grained control over the local endpoint from which a client socket originates. It supports both IPv4 and IPv6 resolution, dual-stack addressing, and wildcard or specific local interfaces.
This method must be called after the socket is constructed and before connect(). It can only be called once; repeated calls will throw. Internally uses getaddrinfo() for resolution and retries all returned addresses until binding succeeds.
| [in] | localHost | A local IP address or hostname to bind to (e.g., "127.0.0.1" or "::1"). |
| [in] | port | Port number to bind to. Use 0 to allow the OS to auto-assign one. |
| SocketException | if resolution or binding fails, or if the socket is already bound. |
|
protected |
Cleans up internal resources and resets the server socket state.
This internal method ensures proper teardown of socket-related resources without throwing exceptions. It is used by destructors and error-handling code to guarantee that:
This method is noexcept-safe and must never throw. It is typically used in destructors, move operations, and failure paths to ensure consistent and exception-safe resource management.
|
protected |
Internal helper that closes the socket and clears address resolution state.
This method performs safe resource cleanup for the client socket. It is intended to be reused across error-handling paths to ensure that partially initialized socket state is properly discarded, avoiding leaks or undefined behavior.
|
protected |
Cleans up internal resources and rethrows the current exception.
This method is used in exception-handling blocks to perform safe cleanup of the ServerSocket's internal state and then rethrow the original exception. It ensures that:
This guarantees consistent resource teardown in exception paths, and supports strong exception safety.
| Rethrows | the currently active exception. |
|
protected |
Cleans up socket resources and rethrows the currently active exception.
This method is intended for use within a catch block to safely clean up a partially initialized or failed Socket before rethrowing the active exception. It ensures that all client-side socket resources are properly released, including the socket descriptor and any resolved address info, before propagating the error.
Internally delegates to cleanup() to:
Then immediately rethrows the current exception using throw;.
| SocketException | Always rethrows the currently active exception |
|
protected |
Cleans up internal resources and throws a SocketException.
This method is used when a fatal socket error occurs during construction or setup. It ensures that:
After cleanup, a SocketException is thrown with the provided error code. This ensures RAII-compliant error handling and prevents resource leaks in failure paths.
| [in] | errorCode | The error code to propagate via SocketException |
| SocketException | Always throws after cleaning up internal state |
|
protected |
Closes the socket, resets internal state, and throws a SocketException.
This method performs safe cleanup of all internal socket resources and throws a SocketException with the specified error code and human-readable message. It is used to centralize error handling during socket creation or connection setup, ensuring that no resources are leaked if initialization fails.
Internally, this method delegates to cleanup() to:
It then throws a SocketException with:
| [in] | errorCode | The error code to report in the thrown SocketException |
| SocketException | Always throws after cleanup |
| void ServerSocket::close | ( | ) |
Closes the server socket and releases its associated system resources.
This method closes the underlying server socket, making it no longer able to accept new client connections. After calling close(), the server socket enters the CLOSED state, and any further operations such as accept(), bind(), or listen() will fail with an exception.
Key details:
Example usage:
| SocketException | If an error occurs while closing the socket (for example, if the underlying system call fails). |
| void Socket::close | ( | ) |
Closes the socket connection and releases associated resources.
Close the socket.
This method performs an orderly shutdown and closure of the socket connection:
The method ensures proper cleanup even if the socket is already closed. After calling close(), the Socket object remains valid but disconnected (isValid() will return false).
| SocketException | If the close operation fails due to:
|
| SocketException | on error. |
| void Socket::connect | ( | int | timeoutMillis = -1 | ) |
Establishes a TCP connection to the remote host with optional timeout control.
Attempts to connect to the remote host and port specified during Socket construction. This method supports both blocking and non-blocking connection attempts, depending on the timeoutMillis parameter.
| [in] | timeoutMillis | Connection timeout in milliseconds:
|
| SocketTimeoutException | If the connection did not complete before the timeout. |
| SocketException | If:
|
| void Socket::discard | ( | std::size_t | n, |
| std::size_t | chunkSize = 1024 ) const |
Discards exactly n bytes from the socket by reading and discarding them.
This method reads and discards n bytes from the socket without returning any data. It is useful in scenarios where part of the stream should be skipped (e.g., headers, fixed-length preambles, corrupted payloads).
The discard operation is performed using a temporary buffer of configurable size, which defaults to 1024 bytes. If the chunk size is 0, the method throws an exception.
| [in] | n | Number of bytes to discard. Must be greater than 0. |
| [in] | chunkSize | Size (in bytes) of the temporary buffer used for reading/discarding. Default is 1024. |
| SocketException | If:
|
|
inlinenodiscardnoexcept |
Get the per-instance default internal buffer size used for buffered read operations.
Returns the current value of _defaultInternalBufferSize, which is used as the fallback size for internal buffering in stream-oriented socket reads when no explicit buffer size is provided.
This value is typically initialized to DefaultBufferSize (4096 bytes), but can be modified using setDefaultInternalBufferSize().
|
inlinenodiscardnoexcept |
Get the current default receive buffer size for accepted client sockets.
Returns the buffer size that will be used when accepting new client connections. This is the value previously set by setDefaultReceiveBufferSize() or the default if not set.
|
inlinenodiscardnoexcept |
Get the current default send buffer size for accepted client sockets.
Returns the send buffer size that will be used when accepting new client connections. This is the value previously set by setDefaultSendBufferSize() or the default if not set.
|
inlinenodiscardprivate |
Get the effective internal buffer size to use for buffered socket read operations.
This helper determines the internal buffer size for read-related operations based on the provided optional value. If internalBufferSize is set, its value is returned directly. If not, the method returns the per-instance _defaultInternalBufferSize, which defaults to DefaultBufferSize (4096 bytes) unless explicitly overridden via setInternalBufferSize().
This internal buffer is used for stream-based operations (e.g. reading strings or protocol lines) and is distinct from the kernel-level socket buffers (SO_RCVBUF, SO_SNDBUF).
| [in] | internalBufferSize | Optional buffer size override for a single operation. |
|
inlinenodiscardprivate |
Get the effective receive buffer size to use for socket read operations.
This helper determines the actual buffer size based on an optional user-provided value. If the parameter is std::nullopt, it returns the per-instance default receive buffer size; otherwise, it returns the explicitly provided value (even if it's 0).
| [in] | recvBufferSize | Optional size. If unset, defaults to _defaultReceiveBufferSize. |
|
inlinenodiscardprivate |
Get the effective send buffer size to use for socket write operations.
This helper determines the actual send buffer size based on an optional user-specified value. If the parameter is std::nullopt, it returns the per-instance default send buffer size. Otherwise, it returns the explicitly specified size (including zero if the caller intends it).
| [in] | sendBufferSize | Optional size. If unset, defaults to _defaultSendBufferSize. |
|
nodiscard |
Retrieves the local IP address this socket is bound to.
This method returns the local interface IP address assigned to the socket, in numeric string format (e.g., "127.0.0.1", "192.168.1.5", or "fe80::1"). It reflects the interface to which the socket is bound — either explicitly via bind() or implicitly by the system during connect() or accept().
If the socket is using IPv6 and the local address is an IPv4-mapped IPv6 address (e.g., ::ffff:192.0.2.1), and convertIPv4Mapped == true, this method will return the simplified IPv4 form ("192.0.2.1").
| [in] | convertIPv4Mapped | Whether to normalize IPv4-mapped IPv6 addresses to plain IPv4 (default = true) |
| SocketException | if the socket is not bound or the address cannot be retrieved. |
|
nodiscard |
Retrieve the local port number to which the server socket is bound.
This method returns the port number that the server socket is currently bound to. This is particularly useful when the socket is bound to port 0, which tells the operating system to automatically assign an available port. You can use this method after binding to discover the actual port being used.
| SocketException | if there is an error retrieving the port number. |
|
nodiscard |
Retrieves the local port number this socket is bound to.
This method returns the port number that the socket is currently bound to on the local system. It can be used after an explicit call to bind(), or implicitly after a successful connect() or accept() where the OS assigns an ephemeral port.
The value is returned in host byte order and reflects the actual bound state of the socket. If the socket is not yet bound, an exception will be thrown.
| SocketException | if the socket is not bound or the port cannot be retrieved. |
|
nodiscard |
Get the local socket address (IP and port) to which the server socket is bound.
Returns a string with the IP address and port in the format "ip:port" (e.g., "127.0.0.1:8080"). Useful for debugging, logging, and displaying server status.
| SocketException | if there is an error retrieving the address. |
|
nodiscard |
Retrieves the full local socket address in the form "IP:port".
This method returns a combined representation of the socket's local IP address and port number, formatted as a string. It is valid after the socket has been bound (explicitly via bind() or implicitly via connect() or accept()).
| [in] | convertIPv4Mapped | Whether to normalize IPv4-mapped IPv6 addresses to pure IPv4 |
| SocketException | if the local address or port cannot be retrieved |
|
nodiscard |
Retrieves the IP address of the remote peer this TCP socket is connected to.
This method returns the remote IP address of the connected peer. It is only valid after a successful connect() or after a socket has been returned by accept().
| [in] | convertIPv4Mapped | Whether to normalize IPv4-mapped IPv6 addresses (default = true) |
| SocketException | if the socket is not connected or the remote address cannot be retrieved |
|
nodiscard |
Retrieves the port number of the remote peer this TCP socket is connected to.
This method returns the TCP port number of the peer to which this socket is currently connected. It is valid after a successful connect() or after a client socket has been accepted from a ServerSocket.
| SocketException | if the socket is not connected or the port cannot be retrieved. |
|
nodiscard |
Get the connected peer's socket address as a formatted string.
Combines the IP address and port of the connected peer into a single human-readable string. This is valid after a successful connect() or after a connection is accepted from a ServerSocket.
| [in] | convertIPv4Mapped | Whether to normalize IPv4-mapped IPv6 addresses. |
| SocketException | if the socket is not connected or the address cannot be retrieved. |
|
inlinenodiscardnoexcept |
Check if the server socket is bound to a local address.
Returns true if the socket has been successfully bound to a local address and port using the bind() method, or false otherwise. This means the socket has reserved a port but is not necessarily accepting connections yet.
Follows the naming and semantics of Java's ServerSocket::isBound().
|
inlinenodiscardnoexcept |
Indicates whether the socket has been explicitly bound to a local address and/or port.
Returns true if the socket has successfully completed a call to one of the bind() overloads. Binding is optional for client sockets, but is often required in advanced scenarios such as:
Binding must occur before the socket is connected. Attempting to bind after connect() will throw.
|
inlinenodiscardnoexcept |
Check if the server socket has been closed.
This method returns true if the socket has been closed (and is no longer usable), or false if it is still open. The logic and naming follow the Java networking API for familiarity.
|
inlinenodiscardnoexcept |
Reports whether the socket has been closed or invalidated.
Returns true if the socket is no longer usable—either because it was explicitly closed, or because the underlying file descriptor has been released or never initialized.
This method does not perform any system-level check or probing. It simply inspects the internal socket descriptor (getSocketFd()) and considers the socket closed if it is equal to INVALID_SOCKET. This reflects the same mechanism used internally for error detection and safety throughout the library.
|
inlinenodiscardnoexcept |
Indicates whether the socket has been successfully connected to a remote host.
Returns true if the socket has completed a successful connection attempt using connect(). This reflects the internal connection state as tracked by the library—it does not actively probe the socket or verify that the connection is still alive at the network layer.
Use this method to check whether it is valid to perform send/receive operations. A socket transitions to the "connected" state only after a successful call to connect() with no subsequent errors or closures.
|
inlinenodiscardnoexcept |
Checks whether the socket's input stream has been shutdown.
Returns true if the socket has been explicitly shutdown for reading via shutdown(ShutdownMode::Read) or shutdown(ShutdownMode::Both). After input shutdown:
This method tracks shutdown state internally—it does not query the operating system (as no portable API exists for that). It reflects the local state at the time of the last shutdown() call on this socket.
|
inlinenodiscardnoexcept |
Check if the server socket is currently listening for incoming connections.
Returns true if the socket has successfully entered the listening state by calling the listen() method, and is ready to accept new client connections. Returns false otherwise.
This complements isBound(), which only tells you if the socket has been bound to a local address.
|
inlinenodiscardnoexcept |
Checks whether the socket's output stream has been shutdown.
Returns true if the socket has been explicitly shutdown for writing via shutdown(ShutdownMode::Write) or shutdown(ShutdownMode::Both). After output shutdown:
This method tracks shutdown state internally—it does not query the operating system, as no portable getsockopt() mechanism exists to detect output shutdown externally.
|
inlinenodiscardnoexcept |
Check whether the server socket is currently open and valid.
This method determines if the server socket has been successfully created and is ready for binding, listening, or accepting connections. It checks whether the underlying socket handle is valid on the current platform.
|
inlinenodiscardnoexcept |
Check if the socket is valid and open for communication.
This method checks if the socket has a valid file descriptor and is ready for communication. A socket is considered valid if it has been successfully created and has not been closed. However, a valid socket is not necessarily connected; use isConnected() to check the connection status.
| void ServerSocket::listen | ( | int | backlog = 128 | ) |
Marks the socket as a passive (listening) socket, ready to accept incoming TCP connection requests.
This method puts the server socket into listening mode, so it can accept incoming client connections using accept().
| SocketException | if the listen operation fails. |
|
delete |
Copy assignment operator (deleted).
ServerSocket objects cannot be copied because they represent unique system resources. Each server socket needs exclusive ownership of its underlying file descriptor and associated resources. Use move semantics (operator=(ServerSocket&&)) instead to transfer ownership between ServerSocket objects.
| [in] | rhs | The ServerSocket to copy from (unused since deleted) |
|
inlinenoexcept |
Move assignment operator for ServerSocket.
Transfers ownership of socket resources from another ServerSocket object to this one. If this socket already owns resources, they are properly cleaned up before the transfer.
The operation is noexcept and provides the strong exception guarantee:
After the move:
| [in] | rhs | The ServerSocket to move resources from. |
Copy assignment operator (deleted) for Socket class.
This operator is explicitly deleted because Socket objects manage unique system resources (socket file descriptors) that cannot be safely duplicated. Each socket must have exclusive ownership of its underlying resources to prevent issues like:
Instead of copying, use move semantics (operator=(Socket&&)) to transfer ownership of a Socket from one object to another. For example:
| [in] | rhs | The Socket object to copy from (unused since deleted) |
Move assignment operator that transfers socket ownership safely.
This operator safely transfers ownership of socket resources from another Socket object while properly managing the current socket's resources. It ensures proper cleanup of existing resources before taking ownership of the new ones.
The operator performs these steps in order:
After the move operation:
| [in,out] | rhs | The source Socket whose resources will be moved. After the move, rhs will be left in a valid but disconnected state. |
| std::string Socket::peek | ( | std::size_t | n | ) | const |
Peeks at incoming data without consuming it.
This method performs a non-destructive read of up to n bytes using the MSG_PEEK flag. It allows inspecting the contents of the socket's receive buffer without removing the data from the queue. This is useful for implementing lookahead parsing, protocol sniffing, or waiting for specific patterns before consuming data.
| [in] | n | Maximum number of bytes to peek at. |
| SocketException | If:
|
|
inline |
Specialization of read<T>() for reading a single buffer of string data.
Reads a variable-length block of data from the socket into the internal receive buffer and returns it as a std::string. This specialization provides optimized handling for raw or text-based data streams where the amount of available data is not known in advance.
Unlike read<T>(), which reads a fixed number of bytes based on the type, this method reads up to the size of the internal buffer and returns whatever data is available, making it ideal for use cases where the protocol layer or application logic defines variable-sized records or streams.
| SocketException | If:
|
|
inlinenodiscard |
Reads a fixed-size, trivially copyable object of type T from the socket.
Performs a binary-safe read of exactly sizeof(T) bytes from the socket and constructs an instance of T from the received data. This method is optimized for reading primitive types and Plain Old Data (POD) structures directly from a binary stream, without any decoding or parsing overhead.
| T | A trivially copyable type to read from the socket. This is enforced at compile time. |
| SocketException | If:
|
| std::string Socket::readAtMost | ( | std::size_t | n | ) | const |
Performs a single best-effort read of up to n bytes from the socket.
This method attempts to read up to n bytes from the socket using a single recv() call. It is designed for responsiveness: it returns as soon as any data is available—whether that's the full n bytes, fewer bytes, or even zero if the connection was closed.
This is a low-overhead, non-looping read ideal for event-driven designs, polling, or non-blocking sockets. It differs from readExact() in that it does not retry or wait for the full amount of data.
| [in] | n | Maximum number of bytes to read in one call. Must be greater than 0. |
| SocketException | If:
|
| std::string Socket::readAtMostWithTimeout | ( | std::size_t | n, |
| int | timeoutMillis ) const |
Attempts a best-effort read of up to n bytes with a timeout constraint.
Waits for the socket to become readable for up to timeoutMillis milliseconds, then performs a single recv() call to read up to n bytes of available data. This method is useful for polling-style or time-sensitive I/O operations where immediate responsiveness is more important than full data delivery.
Unlike readExact(), this method does not loop or retry to satisfy the full size. It returns as soon as data is available, or throws a SocketTimeoutException if no data arrives within the specified timeout window.
| [in] | n | Maximum number of bytes to read in one operation. Must be > 0. |
| [in] | timeoutMillis | Maximum duration to wait for readability, in milliseconds:
|
| SocketTimeoutException | If the socket remains unreadable beyond timeoutMillis. |
| SocketException | If:
|
| std::string Socket::readAvailable | ( | ) | const |
Reads all bytes currently available on the socket without blocking.
Performs a best-effort, non-blocking read of all data that is already available in the socket's input buffer. This method uses platform-specific mechanisms (e.g., FIONREAD or ioctl) to query how many bytes can be read without blocking, then performs a single recv() call to consume and return that data.
This method is useful in event-driven or polling-based systems where you want to quickly drain the socket buffer without waiting for more data to arrive.
| SocketException | If:
|
| std::string Socket::readExact | ( | std::size_t | n | ) | const |
Reads exactly n bytes from the socket into a std::string.
Performs a fully blocking read that continues reading from the socket until the specified number of bytes (n) has been received, or an error or disconnection occurs. This method guarantees exact-length delivery and is suitable for fixed-length binary protocols or framed data.
Internally, it repeatedly calls recv() as needed to handle partial reads. It allocates a string of size n and fills it directly with received data in order, preserving byte order and content integrity.
| [in] | n | The number of bytes to read. Must be greater than zero. |
| SocketException | If:
|
|
inline |
Reads available data from the socket into the provided buffer.
Performs a "best-effort" read operation by attempting to read up to len bytes from the socket into the provided buffer. This method makes a single recv() call and returns immediately with whatever data is available, which may be less than the requested length.
| [out] | buffer | Pointer to pre-allocated memory buffer to store read data. Must be valid and large enough for len bytes. |
| [in] | len | Maximum number of bytes to read (buffer size) |
| SocketException | If:
|
| std::size_t Socket::readIntoAvailable | ( | void * | buffer, |
| std::size_t | bufferSize ) const |
Reads all currently available bytes into the provided buffer without blocking.
This method checks how many bytes are available for reading on the socket using platform-specific ioctl/FIONREAD mechanisms, and reads as many bytes as possible (up to the specified buffer size) into the provided memory buffer. It does not block or wait for additional data to arrive.
This is the low-level, zero-copy variant of readAvailable(), ideal for high-performance applications and protocol parsers that manage their own memory buffers.
| [out] | buffer | Pointer to the memory where received data will be stored. |
| [in] | bufferSize | Maximum number of bytes to store in the buffer. |
| SocketException | If:
|
|
inline |
Reads exactly len bytes into the given buffer (looped recv).
This method guarantees to read exactly the specified number of bytes from the socket into the provided buffer. It will continue reading until either all requested bytes are received or an error occurs. This is useful when reading fixed-length protocol messages or binary data structures where partial reads are not acceptable.
| [out] | buffer | Pointer to pre-allocated memory where data should be written. Must be valid and large enough for len bytes. |
| [in] | len | Number of bytes to read. Method won't return until exactly this many bytes are read or an error occurs. |
| SocketException | If: |
|
protected |
Reads data from the socket into a user-supplied buffer.
This method provides direct access to the socket's receive functionality by reading data into a caller-provided buffer. It supports both "best-effort" single reads and exact-length reads that ensure all requested bytes are received.
| [out] | buffer | Pointer to caller-allocated memory buffer Must be valid and large enough for len bytes |
| [in] | len | Maximum number of bytes to read (buffer size) |
| [in] | exact | If true, method won't return until len bytes are read or an error occurs |
| SocketException | If:
|
|
inline |
Reads a line terminated by '
' from the socket.
This is a convenience method that calls readUntil('
', maxLen, includeDelimiter). It provides backward compatibility and a more intuitive interface for reading newline-terminated data.
| [in] | maxLen | Maximum number of bytes to read (default: 8192) |
| [in] | includeDelimiter | Whether to include the newline in the returned string (default: true) |
| SocketException | on error or if line exceeds maxLen |
|
inline |
Reads a length-prefixed payload using a fixed-size prefix type.
Reads a message that consists of a length prefix followed by a variable-length payload. The prefix type T determines the format and size of the length field. This method is useful for protocols that encode message length as a fixed-size integer header.
+----------------+----------------------+ | Length (T) | Payload (n bytes) | +----------------+----------------------+ |<- sizeof(T) ->|<---- length ------->|
| T | The unsigned integral type used for the length prefix (e.g., uint32_t). Must be a trivially copyable type. |
| SocketException | If:
|
|
inline |
Reads a length-prefixed message with an upper bound check.
Reads a message that consists of a length prefix followed by a variable-length payload. This overload adds protection by validating that the decoded length does not exceed a specified maximum (maxPayloadLen), helping prevent corrupted or maliciously large payloads.
The prefix type T determines the format and size of the length field and is decoded in network byte order using net::fromNetwork().
+----------------+----------------------+ | Length (T) | Payload (n bytes) | +----------------+----------------------+ |<- sizeof(T) ->|<---- length ------->|
| T | The unsigned integral type used for the length prefix (e.g., uint32_t). Must be a trivially copyable type. |
| [in] | maxPayloadLen | Maximum allowed length of the decoded payload in bytes. If the decoded prefix exceeds this, an exception is thrown. |
| SocketException | If:
|
| std::string Socket::readUntil | ( | char | delimiter, |
| std::size_t | maxLen = 8192, | ||
| bool | includeDelimiter = true ) |
Reads data from the socket until a specified delimiter character is encountered.
Reads and accumulates data from the socket until the given delimiter character is found, using the internal buffer for efficient, chunked recv() calls. Unlike byte-at-a-time reads, this method minimizes syscall overhead and improves performance by reading in larger blocks and scanning for the delimiter in memory.
If the delimiter is found, the method returns a string containing all bytes up to (and optionally including) the delimiter. If the delimiter is not found within maxLen bytes, an exception is thrown to prevent unbounded growth or protocol desynchronization.
| [in] | delimiter | The character to search for in the incoming data stream. |
| [in] | maxLen | The maximum number of bytes to read before giving up (default: 8192). |
| [in] | includeDelimiter | Whether to include the delimiter in the returned string (default: true). |
| SocketException | If:
|
| std::size_t Socket::readv | ( | std::span< BufferView > | buffers | ) | const |
Performs a vectorized read into multiple buffers using a single system call.
Reads data into the specified sequence of buffers using scatter/gather I/O. This method fills each buffer in order and returns the total number of bytes read. It is the counterpart to writev() and uses readv() or WSARecv() internally.
| [out] | buffers | A span of BufferView objects describing writable regions. |
| SocketException | If:
|
| std::size_t Socket::readvAll | ( | std::span< BufferView > | buffers | ) | const |
Reads exactly the full contents of all provided buffers.
This method performs a reliable scatter read operation. It guarantees that all bytes described by the buffer span are filled by repeatedly calling readv() until the entire memory region is received or an error occurs.
| [out] | buffers | A span of writable buffer views to fill completely. |
| SocketException | If:
|
| std::size_t Socket::readvAllWithTotalTimeout | ( | std::span< BufferView > | buffers, |
| int | timeoutMillis ) const |
Reads exactly the full contents of all buffers within a timeout.
This method performs a series of vectorized readv() calls to fill the provided BufferView span until all bytes are read or the total timeout expires. A steady clock is used to measure elapsed time across multiple system calls, ensuring the full operation adheres to the timeout limit.
If not all data is read before the timeout elapses, a SocketTimeoutException is thrown.
| [out] | buffers | Span of BufferView objects describing writable memory regions. |
| [in] | timeoutMillis | Maximum allowed duration for the entire read operation, in milliseconds. |
| SocketTimeoutException | If:
|
| SocketException | If:
|
| std::size_t Socket::readvAtMostWithTimeout | ( | std::span< BufferView > | buffers, |
| int | timeoutMillis ) const |
Attempts a single vectorized read into multiple buffers with a timeout.
Waits up to timeoutMillis milliseconds for the socket to become readable, then performs a single readv() operation into the provided buffer views. This method does not retry on partial reads and is suitable for polling-style I/O where responsiveness is more important than completeness.
May read fewer bytes than the total available buffer capacity, depending on what the socket delivers in a single system call. This is a timeout-aware variant of readv() and should be used when non-blocking responsiveness is desired.
| [out] | buffers | Span of writable BufferViews to receive incoming data. |
| [in] | timeoutMillis | Time in milliseconds to wait for readability:
|
| SocketTimeoutException | If the socket does not become readable before timeout. |
| SocketException | If:
|
|
inlineprotectednoexcept |
Resets internal shutdown state flags to false.
This method clears the internal flags that track whether the socket's input or output streams have been shutdown via shutdown(ShutdownMode). It does not reopen or re-enable socket directions at the system level—it only resets the internal state used by isInputShutdown() and isOutputShutdown().
This method is useful when reinitializing or repurposing a Socket object after calling close(), or when transferring ownership during a move assignment where shutdown state is no longer valid.
|
inlinenodiscardprivate |
Resolves effective receive and send buffer sizes from optional user inputs.
If either buffer size is not provided, this method falls back to the per-instance _defaultReceiveBufferSize or _defaultSendBufferSize.
| recv | Optional receive buffer size. |
| send | Optional send buffer size. |
| internal | Optional internal buffer size. |
|
delete |
Default constructor (deleted) for ServerSocket class.
The default constructor is explicitly deleted to prevent the creation of uninitialized ServerSocket objects. Each server socket must be explicitly constructed with a valid port and configuration parameters to ensure correct binding and listening behavior.
|
delete |
Copy constructor (deleted).
This constructor is explicitly deleted because ServerSocket instances manage unique system resources (socket descriptors) that cannot be safely shared or duplicated. Each socket must have exclusive ownership of its underlying system resources to ensure proper cleanup and avoid resource leaks.
Instead of copying, use move semantics (ServerSocket&&) to transfer ownership of a socket between objects.
| [in] | rhs | The ServerSocket to copy from (unused since deleted). |
|
explicit |
Constructs a ServerSocket for listening to incoming TCP connections with full configuration control.
This constructor creates a TCP server socket that supports both IPv4 and IPv6, with flexible options for binding, listening, address selection, address reuse, accept timeouts, and dual-stack (IPv4+IPv6) control.
The constructor performs the following steps:
| [in] | port | The port number to prepare the server socket for (binding will occur according to autoBindListen). |
| [in] | localAddress | The local address/interface to bind to (empty for all interfaces). |
| [in] | autoBindListen | If true (default), automatically binds and listens. If false, user must call them manually. |
| [in] | reuseAddress | If true (default), enables address reuse (see above) before binding. |
| [in] | soTimeoutMillis | Accept timeout in milliseconds for accept(); -1 (default) means block indefinitely. |
| [in] | dualStack | If true (default), enables dual-stack (IPv4+IPv6) for IPv6 sockets. If false, enables IPv6-only mode (no IPv4-mapped addresses). Has no effect for IPv4 sockets. |
| SocketException | If address resolution, socket creation, binding, or socket option configuration fails. |
|
inlinenoexcept |
Move constructor that transfers ownership of server socket resources.
This constructor implements move semantics to efficiently transfer ownership of socket resources from one ServerSocket object to another. It's particularly useful when you need to transfer socket ownership (e.g., returning from functions or storing in containers) without copying the underlying system resources.
The operation provides the strong exception guarantee and is marked noexcept:
After the move:
| [in] | rhs | The ServerSocket to move resources from. |
|
inline |
Set the per-instance default internal buffer size used for buffered read operations.
This method updates the _defaultInternalBufferSize value, which determines the fallback buffer size used by methods like accept() or readLine() when no explicit internalBufferSize is provided.
This does not affect the kernel-level SO_RCVBUF. It applies only to the internal buffering layer used in higher-level stream-oriented reads (e.g., reading lines or strings).
| size | New default buffer size in bytes for this socket/server instance. |
|
inline |
Set the default receive buffer size for accepted client sockets.
This sets the initial buffer size used when accepting new client connections. The buffer size determines how much data can be buffered for reading from the socket before the underlying receive buffer overflows.
| [in] | size | New buffer size in bytes |
|
inline |
Set the default send buffer size for accepted client sockets.
This sets the initial send buffer size used when accepting new client connections. The buffer size determines how much data can be buffered for writing to the socket before the underlying send buffer overflows.
| [in] | size | New send buffer size in bytes |
| void Socket::setInternalBufferSize | ( | std::size_t | newLen | ) |
Sets the size of the internal read buffer used for string operations.
This method controls the size of the internal buffer used by read<std::string>() operations. This is distinct from setReceiveBufferSize(), which controls the operating system's socket buffer (SO_RCVBUF).
| [in] | newLen | New size for the internal buffer in bytes |
| std::bad_alloc | If memory allocation fails |
| void Socket::shutdown | ( | ShutdownMode | how | ) | const |
Shutdown specific communication aspects of the socket.
This method allows for a controlled shutdown of socket communications in one or both directions without closing the socket itself. Unlike close(), which immediately terminates all communications, shutdown() provides finer control over how the connection is terminated.
| [in] | how | Specifies which operations to shut down:
|
| SocketException | If: |
|
delete |
Default constructor (deleted) for Socket class.
The default constructor is explicitly deleted to prevent the creation of uninitialized Socket objects. Each socket must be explicitly constructed with a valid host/port combination or from an accepted client connection.
|
delete |
Copy constructor (deleted) for Socket class.
This constructor is explicitly deleted because Socket objects manage unique system resources (socket file descriptors) that cannot be safely duplicated. Each socket must have exclusive ownership of its underlying resources to prevent issues like:
Instead of copying, use move semantics (Socket&&) to transfer ownership of a Socket from one object to another. For example:
| [in] | rhs | The Socket object to copy from (unused since deleted) |
|
inlinenoexcept |
Move constructor that transfers ownership of socket resources.
Creates a new Socket by taking ownership of another Socket's resources. This constructor is essential for scenarios where Socket objects need to be transferred (e.g., returning from functions, storing in containers) since copying is disabled.
The constructor performs the following:
The moved-from socket (rhs) remains valid but will be in a default-constructed state with no active connection (getSocketFd() = INVALID_SOCKET).
| [in,out] | rhs | The Socket object to move from. After the move, rhs will be left in a valid but disconnected state. |
|
protected |
Wraps an accepted TCP client socket with optional tuning parameters.
This constructor creates a Socket object by taking ownership of a socket descriptor returned by accept(), applying the given address, and configuring buffer sizes, timeouts, and TCP-specific options.
| [in] | client | A connected socket descriptor returned by accept() |
| [in] | addr | The client's address information (from accept()) |
| [in] | len | Length of the address structure |
| [in] | recvBufferSize | OS-level receive buffer size |
| [in] | sendBufferSize | OS-level send buffer size |
| [in] | internalBufferSize | Internal read buffer size |
| [in] | soRecvTimeoutMillis | Timeout for recv()/read() in milliseconds; -1 disables |
| [in] | soSendTimeoutMillis | Timeout for send() in milliseconds; -1 disables |
| [in] | tcpNoDelay | Whether to disable Nagle's algorithm |
| [in] | keepAlive | Whether to enable TCP keep-alive |
| [in] | nonBlocking | Whether to set the socket to non-blocking mode |
| SocketException | If any tuning operation fails after the socket is accepted |
| Socket::Socket | ( | std::string_view | host, |
| Port | port, | ||
| std::optional< std::size_t > | recvBufferSize = std::nullopt, | ||
| std::optional< std::size_t > | sendBufferSize = std::nullopt, | ||
| std::optional< std::size_t > | internalBufferSize = std::nullopt, | ||
| bool | reuseAddress = true, | ||
| int | soRecvTimeoutMillis = -1, | ||
| int | soSendTimeoutMillis = -1, | ||
| bool | dualStack = true, | ||
| bool | tcpNoDelay = true, | ||
| bool | keepAlive = false, | ||
| bool | nonBlocking = false, | ||
| bool | autoConnect = true, | ||
| bool | autoBind = false, | ||
| std::string_view | localAddress = "", | ||
| Port | localPort = 0 ) |
Constructs a TCP client socket, resolves the remote host and port, and optionally binds or connects.
This constructor creates a TCP socket intended for client-side connections. It resolves the specified remote host and port, applies socket-level configuration, and optionally:
The socket supports both IPv4 and IPv6, dual-stack operation, and high-level configuration of timeouts, buffer sizes, and TCP flags like TCP_NODELAY and SO_KEEPALIVE.
| [in] | host | Remote hostname or IP address to connect to |
| [in] | port | Remote TCP port number |
| [in] | recvBufferSize | Optional socket receive buffer size (SO_RCVBUF) |
| [in] | sendBufferSize | Optional socket send buffer size (SO_SNDBUF) |
| [in] | internalBufferSize | Optional internal read buffer size for high-level operations |
| [in] | reuseAddress | Enables SO_REUSEADDR to allow rebinding to the same port |
| [in] | soRecvTimeoutMillis | Timeout for receive operations in milliseconds (SO_RCVTIMEO) |
| [in] | soSendTimeoutMillis | Timeout for send operations in milliseconds (SO_SNDTIMEO) |
| [in] | dualStack | If true, uses AF_UNSPEC to allow IPv6+IPv4 fallback |
| [in] | tcpNoDelay | If true, disables Nagle’s algorithm (TCP_NODELAY) |
| [in] | keepAlive | If true, enables TCP keep-alive probes |
| [in] | nonBlocking | If true, sets the socket to non-blocking mode after creation |
| [in] | autoConnect | If true, immediately performs a blocking connect() to the peer |
| [in] | autoBind | If true, performs a bind() before connecting |
| [in] | localAddress | Local IP to bind to (if autoBind == true) |
| [in] | localPort | Local port to bind to (if autoBind == true) |
| SocketException | If resolution, socket creation, binding, configuration, or connection fails |
|
nodiscard |
Attempt to accept an incoming client connection, waiting up to a specified timeout and returning std::nullopt on timeout.
This method waits for an incoming client connection using the explicitly provided timeoutMillis value, overriding any timeout configured via setSoTimeout(). If a client connects before the timeout expires, a fully configured Socket is returned. Otherwise, std::nullopt is returned instead of throwing.
Readiness is detected using select() via waitReady(timeoutMillis), followed by a call to acceptBlocking(...) if the socket is ready.
If a client is accepted, the resulting Socket is configured using the following options:
Even after readiness is reported, accept() may still fail with EWOULDBLOCK or EAGAIN if the client disconnects in the small window before accept() is invoked. In that case, a SocketException is thrown.
This method is not thread-safe. If used from multiple threads, you must externally synchronize access to the server socket to prevent race conditions.
| [in] | timeoutMillis | Timeout in milliseconds for this call:
|
| [in] | recvBufferSize | Optional receive buffer size (SO_RCVBUF) |
| [in] | sendBufferSize | Optional send buffer size (SO_SNDBUF) |
| [in] | internalBufferSize | Optional internal buffer for read<T>()-style calls |
| [in] | soRecvTimeoutMillis | Receive timeout for the accepted socket (SO_RCVTIMEO); -1 disables |
| [in] | soSendTimeoutMillis | Send timeout for the accepted socket (SO_SNDTIMEO); -1 disables |
| [in] | tcpNoDelay | Whether to disable Nagle’s algorithm (TCP_NODELAY); default: true |
| [in] | keepAlive | Whether to enable TCP keep-alive (SO_KEEPALIVE) |
| [in] | nonBlocking | Whether to set the accepted socket to non-blocking mode |
| SocketException | If the server socket is invalid or accept() fails due to system error |
|
nodiscard |
Attempt to accept an incoming client connection, returning std::nullopt on timeout instead of throwing.
This method waits for an incoming client connection using the timeout configured via setSoTimeout(). If a client is available before the timeout expires, it returns a fully configured Socket object. If no client connects in time, it returns std::nullopt rather than throwing.
Internally, waitReady() is used for readiness detection, followed by acceptBlocking() for the actual accept.
The returned Socket (if any) is configured using the following tuning options:
This method is not thread-safe. Concurrent calls from multiple threads or processes may cause race conditions or spurious failures. Use a mutex to guard access to accept() methods if needed.
| [in] | recvBufferSize | Optional socket receive buffer size (SO_RCVBUF) |
| [in] | sendBufferSize | Optional socket send buffer size (SO_SNDBUF) |
| [in] | internalBufferSize | Optional internal buffer for high-level reads |
| [in] | soRecvTimeoutMillis | Receive timeout (SO_RCVTIMEO) in milliseconds; -1 disables |
| [in] | soSendTimeoutMillis | Send timeout (SO_SNDTIMEO) in milliseconds; -1 disables |
| [in] | tcpNoDelay | Whether to disable Nagle’s algorithm (TCP_NODELAY); default: true |
| [in] | keepAlive | Whether to enable TCP keep-alive (SO_KEEPALIVE) |
| [in] | nonBlocking | Whether to set the accepted socket to non-blocking mode |
| SocketException | if the server socket is invalid or accept() fails for other reasons |
|
nodiscard |
Waits for the server socket to become ready to accept an incoming connection.
This method blocks or polls until the server socket becomes readable, indicating that a new client is attempting to connect. It is used internally by accept() and tryAccept(), but can also be used directly in custom event loops or multiplexed servers.
This method is thread-safe as long as the server socket is not concurrently closed or reconfigured.
| [in] | timeoutMillis | Optional timeout in milliseconds. If omitted, the socket's SO_TIMEOUT is used. |
| SocketException | if:
|
| bool Socket::waitReady | ( | bool | forWrite, |
| int | timeoutMillis ) const |
Waits for the socket to become ready for reading or writing.
This method performs a blocking or timed wait until the socket is ready for either reading or writing, depending on the forWrite parameter. Internally, it uses the select() system call to monitor readiness.
The timeout is specified in milliseconds. A negative timeout value (e.g., -1) causes the method to wait indefinitely until the socket becomes ready. A timeout of 0 performs a non-blocking poll.
| [in] | forWrite | If true, waits for the socket to become writable; if false, waits for it to be readable. |
| [in] | timeoutMillis | Timeout in milliseconds. Use -1 for infinite wait, or 0 for non-blocking polling. |
| true | The socket is ready for I/O. |
| false | The timeout expired before the socket became ready. |
| SocketException | If:
|
|
nodiscard |
Sends data to the socket using a single, best-effort write operation.
Attempts to write up to message.size() bytes from the given std::string_view to the connected socket. This method may return before all data is sent, depending on socket state, system buffer availability, and platform behavior. It performs exactly one send() call and does not retry if the write is partial.
This is the fundamental low-level output method. For complete delivery guarantees, use writeAll() or writeWithTotalTimeout() instead.
| [in] | message | The data to send. Can contain binary content, including null characters. |
| SocketException | If:
|
| size_t Socket::writeAll | ( | std::string_view | message | ) | const |
Writes the entire contents of a message to the socket, retrying as needed.
Ensures that the entire message is transmitted by repeatedly invoking the low-level write() method to handle partial writes. This method blocks until all data is successfully sent, the connection is lost, or an error occurs. It is suitable for protocols or data formats that require full delivery of fixed-size payloads, headers, or serialized objects.
Unlike write(), which may send only part of the input in a single call, this method transparently retries until all bytes are written, making it reliable for complete transmission scenarios (e.g., HTTP requests, framed packets, serialized data).
| [in] | message | The message to send in full. May contain binary or textual content. |
| SocketException | If:
|
| std::size_t Socket::writeAtMostWithTimeout | ( | std::string_view | data, |
| int | timeoutMillis ) const |
Performs a best-effort write with a total timeout.
Waits up to timeoutMillis milliseconds for the socket to become writable, then attempts a single send() operation to write up to data.size() bytes. This method does not retry on partial writes and is designed for time-sensitive, latency-focused applications.
This is a timeout-aware counterpart to write() that returns early in the event of timeout or connection closure. Use this when you need responsiveness rather than guaranteed delivery.
| [in] | data | The data to send. |
| [in] | timeoutMillis | Maximum time to wait for writability, in milliseconds:
|
| SocketTimeoutException | If the socket does not become writable within timeoutMillis. |
| SocketException | If:
|
| std::size_t Socket::writeFrom | ( | const void * | data, |
| std::size_t | len ) const |
Writes up to len bytes from a raw memory buffer in a single send call.
This method sends data directly from a raw memory pointer using a best-effort write. It may write fewer bytes than requested, depending on socket buffer availability. It is the low-level counterpart to write(std::string_view) and avoids constructing or copying into strings.
| [in] | data | Pointer to the memory to write. |
| [in] | len | Number of bytes to send. |
| SocketException | If:
|
| std::size_t Socket::writeFromAll | ( | const void * | data, |
| std::size_t | len ) const |
Writes all bytes from a raw memory buffer, retrying until complete.
This method repeatedly calls send() until the full len bytes of the buffer are successfully transmitted. It guarantees that all bytes are written, or throws an exception on failure. This is the raw-buffer equivalent of writeAll().
| [in] | data | Pointer to the binary buffer to send. |
| [in] | len | Number of bytes to transmit. |
| SocketException | If:
|
|
inline |
Writes a length-prefixed payload using a fixed-size integral prefix.
Sends a message that consists of a length prefix followed by the actual payload. The prefix is encoded in network byte order to ensure cross-platform compatibility.
+----------------+----------------------+ | Length (T) | Payload (n bytes) | +----------------+----------------------+ |<- sizeof(T) ->|<---- length ------->|
| T | The unsigned integral type used for the length prefix (e.g., uint32_t). Must be trivially copyable. |
| [in] | payload | The payload data to send. The length of this view will be encoded as the prefix and must not exceed the maximum representable value of type T. |
| SocketException | If:
|
|
inline |
Writes a binary payload prefixed with its length using a fixed-size integer type.
Sends a length-prefixed binary message, where the prefix is a fixed-size integral type T followed by a raw binary buffer. This version avoids constructing a temporary std::string, making it efficient for zero-copy binary protocols and high-performance I/O paths.
+----------------+----------------------+ | Length (T) | Payload (n bytes) | +----------------+----------------------+ |<- sizeof(T) ->|<---- len --------->|
| T | The unsigned integral type used for the length prefix (e.g., uint32_t). Must be a trivially copyable type. |
| [in] | data | Pointer to the binary payload data. |
| [in] | len | Number of bytes to write from data. |
| SocketException | If:
|
| std::size_t Socket::writev | ( | std::span< const std::string_view > | buffers | ) | const |
Writes multiple buffers in a single system call using scatter/gather I/O.
This method efficiently writes multiple non-contiguous buffers to the socket using platform-specific vectorized I/O calls. It is ideal for sending structured packets, headers + body, or other segmented data without concatenating them.
| [in] | buffers | A span of string views to send as a scatter/gather I/O batch. |
| SocketException | If:
|
| std::size_t Socket::writevAll | ( | std::span< const std::string_view > | buffers | ) | const |
Writes all buffers fully using vectorized I/O with automatic retry on partial sends.
Ensures that the entire contents of all buffers in the given span are fully transmitted, retrying as needed. This is the guaranteed-delivery counterpart to writev().
| [in] | buffers | A span of string fragments to send as a contiguous logical payload. |
| SocketException | If:
|
| std::size_t Socket::writevFrom | ( | std::span< const BufferView > | buffers | ) | const |
Writes multiple raw memory regions using vectorized I/O.
Sends the contents of all buffers in the given span using scatter/gather I/O. This performs a single system call (writev() on POSIX, WSASend() on Windows), and may transmit fewer bytes than requested. Use writevFromAll() for full delivery.
| [in] | buffers | A span of BufferView elements (data + size). |
| SocketException | If:
|
| std::size_t Socket::writevFromAll | ( | std::span< BufferView > | buffers | ) | const |
Writes all raw memory regions fully using scatter/gather I/O.
This method guarantees full delivery of all bytes across the given buffer span. Internally retries writevFrom() until every buffer is fully written. This is the binary-safe, zero-copy equivalent of writevAll().
| [in] | buffers | A span of raw buffers to send completely. |
| SocketException | If:
|
| std::size_t Socket::writevFromWithTotalTimeout | ( | std::span< BufferView > | buffers, |
| int | timeoutMillis ) const |
Writes all raw memory buffers fully within a timeout using scatter I/O.
Sends multiple binary buffers using scatter/gather I/O, retrying partial writes as needed until all data is delivered or the specified timeout period elapses. If the timeout expires before completing the transmission, a SocketTimeoutException is thrown.
This is the binary-buffer equivalent of writevWithTotalTimeout(), intended for use with low-level, structured protocols or custom serialization layers.
| [in] | buffers | A span of BufferView objects representing raw memory regions to send. |
| [in] | timeoutMillis | Total timeout duration in milliseconds across all write attempts. |
| SocketTimeoutException | If:
|
| SocketException | If:
|
| std::size_t Socket::writevWithTotalTimeout | ( | std::span< const std::string_view > | buffers, |
| int | timeoutMillis ) const |
Writes all buffers fully within a total timeout using vectorized I/O.
Sends the contents of all buffers in the provided span using scatter/gather I/O. Retries partial sends as needed, resuming from where the last send left off. The entire operation must complete within timeoutMillis milliseconds or a SocketTimeoutException will be thrown.
This method guarantees that all data across all buffers will be sent in order—or none at all. It is the timeout-aware variant of writevAll() and suitable for time-bounded, multi-buffer transmission (e.g., structured headers + body).
| [in] | buffers | Span of string views representing logically distinct memory segments to send in order. |
| [in] | timeoutMillis | Total allowed duration in milliseconds to complete the operation. |
| SocketTimeoutException | If:
|
| SocketException | If:
|
| std::size_t Socket::writeWithTotalTimeout | ( | std::string_view | data, |
| int | timeoutMillis ) const |
Writes the full payload with a total timeout across all retries.
Repeatedly attempts to send the entire contents of data, retrying partial writes as needed. The complete operation must finish within timeoutMillis milliseconds or it will throw a SocketTimeoutException.
This method ensures full delivery like writeAll(), but it is time-bounded by wall-clock time. It is suitable for real-time or responsiveness-sensitive applications where you must send everything or fail within a deadline.
| [in] | data | The data to send. |
| [in] | timeoutMillis | Maximum time in milliseconds to send the full payload. |
| SocketTimeoutException | If:
|
| SocketException | If:
|
|
overridenoexcept |
Destructor that automatically closes the server socket and releases all associated resources.
This destructor ensures proper cleanup of system resources when a ServerSocket object is destroyed:
The destructor is marked noexcept to prevent exception propagation during stack unwinding, as per C++ best practices. Any errors that occur during cleanup are logged but not thrown.
|
overridenoexcept |
Destructs the Socket object, closing connections and freeing resources.
This destructor ensures proper cleanup of all resources owned by the Socket:
The destructor is marked noexcept to prevent exception propagation during stack unwinding, as per C++ best practices. Any errors that occur during cleanup (e.g., socket closure failures) are ignored.
|
friend |
Grants ServerSocket access to private members.
ServerSocket needs access to Socket's private members during accept() operations to: