jsocketpp 1.0
A cross-platform C++20 socket library.
Loading...
Searching...
No Matches

TCP client connection abstraction (Java-like interface). More...

#include <Socket.hpp>

Inheritance diagram for jsocketpp::Socket:
Collaboration diagram for jsocketpp::Socket:

Public Member Functions

 Socket ()=delete
 Default constructor (deleted) for Socket class.
 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.
 Socket (const Socket &rhs)=delete
 Copy constructor (deleted) for Socket class.
 Socket (Socket &&rhs) noexcept
 Move constructor that transfers ownership of socket resources.
Socketoperator= (const Socket &rhs)=delete
 Copy assignment operator (deleted) for Socket class.
Socketoperator= (Socket &&rhs) noexcept
 Move assignment operator that transfers socket ownership safely.
 ~Socket () noexcept override
 Destructs the Socket object, closing connections and freeing resources.
void bind (std::string_view localHost, Port port)
 Binds the client socket to a specific local IP address and/or port.
void bind (Port port)
 Binds the client socket to all interfaces (INADDR_ANY) using the specified port.
void bind ()
 Binds the client socket to all interfaces using an ephemeral port.
bool isBound () const noexcept
 Indicates whether the socket has been explicitly bound to a local address and/or port.
bool isConnected () const noexcept
 Indicates whether the socket has been successfully connected to a remote host.
std::string getLocalIp (bool convertIPv4Mapped=true) const
 Retrieves the local IP address this socket is bound to.
Port getLocalPort () const
 Retrieves the local port number this socket is bound to.
std::string getLocalSocketAddress (bool convertIPv4Mapped=true) const
 Retrieves the full local socket address in the form "IP:port".
std::string getRemoteIp (bool convertIPv4Mapped=true) const
 Retrieves the IP address of the remote peer this TCP socket is connected to.
Port getRemotePort () const
 Retrieves the port number of the remote peer this TCP socket is connected to.
std::string getRemoteSocketAddress (bool convertIPv4Mapped=true) const
 Get the connected peer's socket address as a formatted string.
void connect (int timeoutMillis=-1)
 Establishes a TCP connection to the remote host with optional timeout control.
template<typename T>
read ()
 Reads a fixed-size, trivially copyable object of type T from the socket.
std::string readExact (std::size_t n) const
 Reads exactly n bytes from the socket into a std::string.
std::string 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 readLine (const std::size_t maxLen=8192, const bool includeDelimiter=true)
 Reads a line terminated by '
' from the socket.
std::string readAtMost (std::size_t n) const
 Performs a single best-effort read of up to n bytes from the socket.
std::size_t readInto (void *buffer, const std::size_t len) const
 Reads available data from the socket into the provided buffer.
std::size_t readIntoExact (void *buffer, const std::size_t len) const
 Reads exactly len bytes into the given buffer (looped recv).
std::string 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 readPrefixed ()
 Reads a length-prefixed payload using a fixed-size prefix type.
template<typename T>
std::string readPrefixed (const std::size_t maxPayloadLen)
 Reads a length-prefixed message with an upper bound check.
std::string readAvailable () const
 Reads all bytes currently available on the socket without blocking.
std::size_t readIntoAvailable (void *buffer, std::size_t bufferSize) const
 Reads all currently available bytes into the provided buffer without blocking.
std::size_t readv (std::span< BufferView > buffers) const
 Performs a vectorized read into multiple buffers using a single system call.
std::size_t readvAll (std::span< BufferView > buffers) const
 Reads exactly the full contents of all provided buffers.
std::size_t readvAllWithTotalTimeout (std::span< BufferView > buffers, int timeoutMillis) const
 Reads exactly the full contents of all buffers within a timeout.
std::size_t readvAtMostWithTimeout (std::span< BufferView > buffers, int timeoutMillis) const
 Attempts a single vectorized read into multiple buffers with a timeout.
std::string peek (std::size_t n) const
 Peeks at incoming data without consuming it.
void discard (std::size_t n, std::size_t chunkSize=1024) const
 Discards exactly n bytes from the socket by reading and discarding them.
void close ()
 Closes the socket connection and releases associated resources.
void shutdown (ShutdownMode how) const
 Shutdown specific communication aspects of the socket.
std::size_t write (std::string_view message) const
 Sends data to the socket using a single, best-effort write operation.
std::size_t 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 writePrefixed (const std::string_view payload)
 Writes a length-prefixed payload using a fixed-size integral prefix.
template<typename T>
std::size_t 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 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 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 writeAtMostWithTimeout (std::string_view data, int timeoutMillis) const
 Performs a best-effort write with a total timeout.
std::size_t 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 writeFromAll (const void *data, std::size_t len) const
 Writes all bytes from a raw memory buffer, retrying until complete.
std::size_t writeWithTotalTimeout (std::string_view data, int timeoutMillis) const
 Writes the full payload with a total timeout across all retries.
std::size_t 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 writevFrom (std::span< const BufferView > buffers) const
 Writes multiple raw memory regions using vectorized I/O.
std::size_t writevFromAll (std::span< BufferView > buffers) const
 Writes all raw memory regions fully using scatter/gather I/O.
std::size_t writevFromWithTotalTimeout (std::span< BufferView > buffers, int timeoutMillis) const
 Writes all raw memory buffers fully within a timeout using scatter I/O.
void setInternalBufferSize (std::size_t newLen)
 Sets the size of the internal read buffer used for string operations.
bool isValid () const noexcept
 Check if the socket is valid and open for communication.
bool waitReady (bool forWrite, int timeoutMillis) const
 Waits for the socket to become ready for reading or writing.
bool isClosed () const noexcept
 Reports whether the socket has been closed or invalidated.
bool isInputShutdown () const noexcept
 Checks whether the socket's input stream has been shutdown.
bool isOutputShutdown () const noexcept
 Checks whether the socket's output stream has been shutdown.
template<>
std::string read ()
 Specialization of read<T>() for reading a single buffer of string data.
Public Member Functions inherited from jsocketpp::SocketOptions
 SocketOptions ()=delete
 Default constructor (deleted) for SocketOptions base class.
 SocketOptions (const SOCKET sock) noexcept
 Initializes the socket option interface with a specific socket descriptor.
virtual ~SocketOptions ()=default
 Virtual destructor for safe polymorphic destruction.
 SocketOptions (const SocketOptions &)=delete
 Copy constructor (deleted) for SocketOptions.
 SocketOptions (SocketOptions &&) noexcept=default
 Move constructor for SocketOptions.
SocketOptionsoperator= (const SocketOptions &)=delete
 Copy assignment operator (deleted) for SocketOptions.
SocketOptionsoperator= (SocketOptions &&) noexcept=default
 Move assignment operator for SocketOptions.
SOCKET getSocketFd () const noexcept
 Retrieves the native socket handle (file descriptor or OS-level handle).
void setOption (int level, int optName, int value)
 Sets a low-level socket option on the underlying socket.
void setOption (int level, int optName, const void *value, socklen_t len)
 Sets a low-level socket option using a structured or binary value.
int getOption (int level, int optName) const
 Retrieves the current value of a low-level socket option.
void getOption (int level, int optName, void *result, socklen_t *len) const
 Retrieves a socket option into a structured or binary buffer.
void setReuseAddress (bool on)
 Enables or disables the SO_REUSEADDR socket option.
bool getReuseAddress () const
 Queries whether the socket is currently configured to allow address reuse.
void setReceiveBufferSize (std::size_t size)
 Sets the socket's receive buffer size (SO_RCVBUF).
int getReceiveBufferSize () const
 Retrieves the current receive buffer size (SO_RCVBUF) of the socket.
void setSendBufferSize (std::size_t size)
 Sets the socket's send buffer size (SO_SNDBUF).
int getSendBufferSize () const
 Retrieves the current send buffer size (SO_SNDBUF) of the socket.
void setSoLinger (bool enable, int seconds)
 Configures the socket's linger behavior (SO_LINGER) during close.
std::pair< bool, int > getSoLinger () const
 Retrieves the current SO_LINGER configuration of the socket.
void setKeepAlive (bool on)
 Enables or disables TCP-level keepalive behavior on the socket (SO_KEEPALIVE).
bool getKeepAlive () const
 Checks whether TCP-level keepalive (SO_KEEPALIVE) is currently enabled.
void setSoRecvTimeout (int millis)
 Sets the socket receive timeout (SO_RCVTIMEO) in milliseconds.
void setSoSendTimeout (int millis)
 Sets the socket send timeout (SO_SNDTIMEO) in milliseconds.
int getSoRecvTimeout () const
 Retrieves the socket receive timeout (SO_RCVTIMEO) in milliseconds.
int getSoSendTimeout () const
 Retrieves the socket send timeout (SO_SNDTIMEO) in milliseconds.
void setNonBlocking (bool nonBlocking)
 Enables or disables non-blocking mode on the socket.
bool getNonBlocking () const
 Queries whether the socket is currently in non-blocking mode.
void setTcpNoDelay (bool on)
 Enables or disables Nagle’s algorithm (TCP_NODELAY) on TCP sockets.
bool getTcpNoDelay () const
 Queries whether Nagle's algorithm (TCP_NODELAY) is currently disabled.
void setBroadcast (bool on)
 Enables or disables the ability to send UDP broadcast messages.
bool getBroadcast () const
 Checks whether the socket is currently allowed to send broadcast messages.
void setIPv6Only (bool enable)
 Enables or disables IPV6_V6ONLY mode for IPv6-capable sockets.
bool getIPv6Only () const
 Queries whether the IPV6_V6ONLY option is enabled on this socket.
void setReusePort (const bool enable)
 Enables or disables the SO_REUSEPORT socket option.
bool getReusePort () const
 Checks whether the SO_REUSEPORT option is currently enabled on the socket.
void setMulticastTTL (int ttl)
 Set the default multicast hop limit / TTL for this socket.
int getMulticastTTL () const
 Get the socket’s default multicast hop limit / TTL.
void setMulticastLoopback (bool enable)
 Enable or disable multicast loopback for this socket.
bool getMulticastLoopback () const
 Read the socket’s multicast loopback flag.
void setMulticastInterfaceIPv4 (in_addr addr)
 Select the outgoing IPv4 interface for multicast.
void setMulticastInterfaceIPv6 (unsigned int ifindex)
 Select the outgoing IPv6 interface for multicast.
void joinGroupIPv4 (in_addr group, in_addr iface)
 Join an IPv4 any-source multicast (ASM) group on a specific interface.
void leaveGroupIPv4 (in_addr group, in_addr iface)
 Leave a previously joined IPv4 multicast group on a specific interface.
void joinGroupIPv6 (in6_addr group, unsigned int ifindex)
 Join an IPv6 any-source multicast (ASM) group on a specific interface index.
void leaveGroupIPv6 (in6_addr group, unsigned int ifindex)
 Leave a previously joined IPv6 multicast group on a specific interface index.

Protected Member Functions

 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.
std::size_t readIntoInternal (void *buffer, std::size_t len, bool exact=false) const
 Reads data from the socket into a user-supplied buffer.
void cleanup ()
 Internal helper that closes the socket and clears address resolution state.
void cleanupAndThrow (int errorCode)
 Closes the socket, resets internal state, and throws a SocketException.
void cleanupAndRethrow ()
 Cleans up socket resources and rethrows the currently active exception.
void resetShutdownFlags () noexcept
 Resets internal shutdown state flags to false.
Protected Member Functions inherited from jsocketpp::SocketOptions
void setSocketFd (const SOCKET sock) noexcept
 Updates the socket descriptor used by this object.
virtual bool isPassiveSocket () const noexcept
 Indicates whether the socket behaves as a passive (listening) socket.

Private Attributes

sockaddr_storage _remoteAddr
 (portability)
socklen_t _remoteAddrLen = 0
 Length of remote address (for recvfrom/recvmsg).
internal::AddrinfoPtr _cliAddrInfo = nullptr
 Address info for connection (from getaddrinfo).
addrinfo * _selectedAddrInfo = nullptr
 Selected address info for connection.
std::vector< char > _internalBuffer
 Internal buffer for read operations, not thread-safe.
bool _isBound = false
 True if the socket is bound to an address.
bool _isConnected = false
 True if the socket is connected to a remote peer.
bool _inputShutdown = false
 True if input side is shutdown (recv disabled).
bool _outputShutdown = false
 True if output side is shutdown (send disabled).

Friends

class ServerSocket
 Grants ServerSocket access to private members.

Additional Inherited Members

Static Protected Member Functions inherited from jsocketpp::SocketOptions
static bool is_ipv4_multicast (const in_addr v4)
 Test whether an IPv4 address is in the multicast range (224.0.0.0/4).
static bool is_ipv6_multicast (const in6_addr &v6)
 Test whether an IPv6 address is in the multicast range (ff00::/8).
static int detectFamily (SOCKET fd)
 Determine the address family (AF_INET or AF_INET6) of a socket.

Detailed Description

TCP client connection abstraction (Java-like interface).

The Socket class represents a TCP connection between your application and a remote host. It provides a high-level, easy-to-use, and cross-platform API for creating, connecting, sending, and receiving data over TCP sockets. Its interface is inspired by Java's Socket class, but uses modern C++20 features.

Key Features

  • Connect to remote hosts using hostnames or IP addresses (IPv4/IPv6).
  • Blocking or timeout-enabled connect for fine-grained control over connection attempts.
  • Safe resource management: sockets are closed automatically when the object is destroyed.
  • Read/write interface for sending and receiving binary data or text.
  • Move-only: socket resources are never accidentally copied.
  • Exception-based error handling via SocketException.
  • Fine-grained control: configure timeouts, non-blocking mode, TCP_NODELAY, SO_KEEPALIVE, etc.

Typical Usage Example

#include <iostream>
int main() {
try {
jsocketpp::Socket sock("example.com", 8080); // Connect to example.com:8080
sock.connect(3000); // Try to connect with 3-second timeout
sock.write("GET / HTTP/1.0\r\n\r\n");
std::string response = sock.read<std::string>();
std::cout << "Received: " << response << std::endl;
sock.close();
} catch (const jsocketpp::SocketException& ex) {
std::cerr << "Socket error: " << ex.what() << std::endl;
}
}
TCP client socket abstraction for jsocketpp.
Represents socket-related errors in the jsocketpp library.
Definition SocketException.hpp:63
TCP client connection abstraction (Java-like interface).
Definition Socket.hpp:93
int main()
Definition client.cpp:89

Internal Buffer

Error Handling

  • Almost all methods throw jsocketpp::SocketException on error (e.g., connect failure, write error, etc).
  • You should catch exceptions to handle network errors gracefully.

Thread Safety

  • Not thread-safe. Use a separate Socket object per thread if needed.

Platform Support

  • Windows, Linux, macOS. Handles all necessary platform differences internally.

Advanced Usage

See Also

Member Data Documentation

◆ _cliAddrInfo

internal::AddrinfoPtr jsocketpp::Socket::_cliAddrInfo = nullptr
private

Address info for connection (from getaddrinfo).

◆ _inputShutdown

bool jsocketpp::Socket::_inputShutdown = false
private

True if input side is shutdown (recv disabled).

◆ _internalBuffer

std::vector<char> jsocketpp::Socket::_internalBuffer
private

Internal buffer for read operations, not thread-safe.

◆ _isBound

bool jsocketpp::Socket::_isBound = false
private

True if the socket is bound to an address.

◆ _isConnected

bool jsocketpp::Socket::_isConnected = false
private

True if the socket is connected to a remote peer.

◆ _outputShutdown

bool jsocketpp::Socket::_outputShutdown = false
private

True if output side is shutdown (send disabled).

◆ _remoteAddr

sockaddr_storage jsocketpp::Socket::_remoteAddr
private

(portability)

sockaddr_in for IPv4; sockaddr_in6 for IPv6; sockaddr_storage for both

◆ _remoteAddrLen

socklen_t jsocketpp::Socket::_remoteAddrLen = 0
mutableprivate

Length of remote address (for recvfrom/recvmsg).

◆ _selectedAddrInfo

addrinfo* jsocketpp::Socket::_selectedAddrInfo = nullptr
private

Selected address info for connection.


The documentation for this class was generated from the following files: