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

TCP server socket abstraction for cross-platform C++ networking. More...

#include <ServerSocket.hpp>

Inheritance diagram for jsocketpp::ServerSocket:
Collaboration diagram for jsocketpp::ServerSocket:

Public Member Functions

 ServerSocket ()=delete
 Default constructor (deleted) for ServerSocket class.
 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.
std::string getLocalIp (bool convertIPv4Mapped=true) const
 Returns the local IP address this server socket is bound to.
Port getLocalPort () const
 Retrieve the local port number to which the server socket is bound.
std::string getLocalSocketAddress () const
 Get the local socket address (IP and port) to which the server socket is bound.
 ServerSocket (const ServerSocket &rhs)=delete
 Copy constructor (deleted).
ServerSocketoperator= (const ServerSocket &rhs)=delete
 Copy assignment operator (deleted).
 ServerSocket (ServerSocket &&rhs) noexcept
 Move constructor that transfers ownership of server socket resources.
ServerSocketoperator= (ServerSocket &&rhs) noexcept
 Move assignment operator for ServerSocket.
 ~ServerSocket () noexcept override
 Destructor that automatically closes the server socket and releases all associated resources.
void bind ()
 Binds the server socket to the configured port and network interface.
bool isBound () const noexcept
 Check if the server socket is bound to a local address.
void listen (int backlog=128)
 Marks the socket as a passive (listening) socket, ready to accept incoming TCP connection requests.
bool isListening () const noexcept
 Check if the server socket is currently listening for incoming connections.
Socket 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 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< SockettryAccept (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< SockettryAccept (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 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< SocketacceptNonBlocking (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< SocketacceptAsync (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 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 close ()
 Closes the server socket and releases its associated system resources.
bool isValid () const noexcept
 Check whether the server socket is currently open and valid.
bool isClosed () const noexcept
 Check if the server socket has been closed.
bool waitReady (std::optional< int > timeoutMillis=std::nullopt) const
 Waits for the server socket to become ready to accept an incoming connection.
void setSoTimeout (const int timeoutMillis)
 Set the logical timeout (in milliseconds) for accepting client connections.
int getSoTimeout () const noexcept
 Get the logical timeout (in milliseconds) for accept operations.
void setDefaultReceiveBufferSize (const std::size_t size)
 Set the default receive buffer size for accepted client sockets.
std::size_t getDefaultReceiveBufferSize () const noexcept
 Get the current default receive buffer size for accepted client sockets.
void setDefaultSendBufferSize (const std::size_t size)
 Set the default send buffer size for accepted client sockets.
std::size_t getDefaultSendBufferSize () const noexcept
 Get the current default send buffer size for accepted client sockets.
void setDefaultInternalBufferSize (const std::size_t size)
 Set the per-instance default internal buffer size used for buffered read operations.
std::size_t getDefaultInternalBufferSize () const noexcept
 Get the per-instance default internal buffer size used for buffered read operations.
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

void cleanup ()
 Cleans up internal resources and resets the server socket state.
void cleanupAndThrow (int errorCode)
 Cleans up internal resources and throws a SocketException.
void cleanupAndRethrow ()
 Cleans up internal resources and rethrows the current exception.
bool isPassiveSocket () const noexcept override
 Identifies this socket as a passive (listening) socket.
Protected Member Functions inherited from jsocketpp::SocketOptions
void setSocketFd (const SOCKET sock) noexcept
 Updates the socket descriptor used by this object.

Private Member Functions

std::size_t getEffectiveReceiveBufferSize (const std::optional< std::size_t > recvBufferSize) const
 Get the effective receive buffer size to use for socket read operations.
std::size_t getEffectiveSendBufferSize (std::optional< std::size_t > sendBufferSize) const
 Get the effective send buffer size to use for socket write operations.
std::size_t 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 > 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.

Private Attributes

internal::AddrinfoPtr _srvAddrInfo = nullptr
 Address info for binding (from getaddrinfo).
addrinfo * _selectedAddrInfo = nullptr
 Selected address info for binding.
Port _port
 Port number the server will listen on.
bool _isBound = false
 True if the server socket is bound.
bool _isListening = false
 True if the server socket is listening.
int _soTimeoutMillis = -1
 Timeout for accept(); -1 = no timeout, 0 = poll, >0 = timeout in milliseconds.
std::size_t _defaultReceiveBufferSize
 Default buffer size used for accepted client sockets when no specific size is provided.
std::size_t _defaultSendBufferSize = DefaultBufferSize
 Default send buffer size for accepted client sockets.
std::size_t _defaultInternalBufferSize
 Default internal buffer size for accepted client sockets, used by some read() methods.

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 server socket abstraction for cross-platform C++ networking.

The ServerSocket class provides a high-level, Java-like interface to create TCP server sockets in C++20, supporting both IPv4 and IPv6, and working on both Windows and Unix-like systems.

Overview

ServerSocket is designed to simplify the creation of network server applications. It allows you to:

  • Bind to a specified port (optionally on a specific address/interface)
  • Listen for incoming connections
  • Accept client connections as new Socket objects
  • Clean up resources automatically (RAII)

This class handles platform differences (such as Winsock vs BSD Sockets) internally, so you can write portable code.

Typical Usage

Here’s how you can use ServerSocket to create a simple TCP echo server:

#include <iostream>
int main() {
try {
// Create a server socket listening on port 12345 (all interfaces, dual-stack IPv4/IPv6)
ServerSocket server(12345);
server.bind();
server.listen();
std::cout << "Server is listening on port 12345..." << std::endl;
while (true) {
Socket client = server.accept();
std::string remoteAddr = client.getRemoteSocketAddress();
std::cout << "Accepted connection from " << remoteAddr << std::endl;
// Echo loop: read a string, send it back
std::string message = client.read<std::string>();
client.write(message);
}
} catch (const socket_exception& e) {
std::cerr << "Server error: " << e.what() << std::endl;
}
return 0;
}
TCP server socket abstraction for jsocketpp.
TCP client socket abstraction for jsocketpp.
TCP client connection abstraction (Java-like interface).
Definition Socket.hpp:93
int main()
Definition client.cpp:89
ServerSocket()=delete
Default constructor (deleted) for ServerSocket class.
std::size_t write(std::string_view message) const
Sends data to the socket using a single, best-effort write operation.
Definition Socket.cpp:418
std::string getRemoteSocketAddress(bool convertIPv4Mapped=true) const
Get the connected peer's socket address as a formatted string.
Definition Socket.cpp:413
T read()
Reads a fixed-size, trivially copyable object of type T from the socket.
Definition Socket.hpp:947

Key Features

  • Cross-platform: Windows and Linux/Unix support
  • IPv4 & IPv6: Automatic dual-stack support if available
  • Resource management: RAII ensures sockets are closed automatically
  • Error handling: Throws exceptions on error for robust applications
  • Customizable: Control backlog, address reuse, blocking/non-blocking modes, etc.

Basic API

  • ServerSocket(port): Construct with a port to listen on.
  • bind(): Bind the server to the selected address and port.
  • listen(): Start listening for connections.
  • accept(): Accept a new client and return a Socket.
  • close(): Close the server socket (also called automatically in destructor).
Note
  • Not thread-safe. Each ServerSocket instance should be used from a single thread at a time, unless external synchronization is applied. Concurrent calls to methods like accept() from multiple threads may result in undefined behavior.
  • After calling accept(), you should use the returned Socket object to communicate with the client.
  • The server socket only accepts TCP connections. Use DatagramSocket for UDP.
  • Exceptions are thrown as SocketException for error conditions.

See Also

Member Function Documentation

◆ getLocalIp()

std::string ServerSocket::getLocalIp ( bool convertIPv4Mapped = true) const
nodiscard

Returns the local IP address this server socket is bound to.

Retrieves the numeric IP address (IPv4 or IPv6) that the server socket is bound to. If the socket is bound to a wildcard interface (e.g., "0.0.0.0" or "::"), the wildcard address is returned as-is.

If the address is an IPv4-mapped IPv6 (::ffff:a.b.c.d) and convertIPv4Mapped is true, it is converted to its original IPv4 representation (e.g., "192.168.0.10").

Parameters
convertIPv4MappedWhether to convert IPv4-mapped IPv6 addresses to plain IPv4. Default is true.
Returns
Local IP address as a string (e.g., "127.0.0.1", "::1", "0.0.0.0").
Exceptions
SocketExceptionif the socket is invalid or the address cannot be retrieved.

Member Data Documentation

◆ _defaultInternalBufferSize

std::size_t jsocketpp::ServerSocket::_defaultInternalBufferSize
private
Initial value:
=
constexpr std::size_t DefaultBufferSize
Default internal buffer size (in bytes) for socket read operations.
Definition common.hpp:434

Default internal buffer size for accepted client sockets, used by some read() methods.

◆ _defaultReceiveBufferSize

std::size_t jsocketpp::ServerSocket::_defaultReceiveBufferSize
private
Initial value:

Default buffer size used for accepted client sockets when no specific size is provided.

◆ _defaultSendBufferSize

std::size_t jsocketpp::ServerSocket::_defaultSendBufferSize = DefaultBufferSize
private

Default send buffer size for accepted client sockets.

◆ _isBound

bool jsocketpp::ServerSocket::_isBound = false
private

True if the server socket is bound.

◆ _isListening

bool jsocketpp::ServerSocket::_isListening = false
private

True if the server socket is listening.

◆ _port

Port jsocketpp::ServerSocket::_port
private

Port number the server will listen on.

◆ _selectedAddrInfo

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

Selected address info for binding.

◆ _soTimeoutMillis

int jsocketpp::ServerSocket::_soTimeoutMillis = -1
private

Timeout for accept(); -1 = no timeout, 0 = poll, >0 = timeout in milliseconds.

◆ _srvAddrInfo

internal::AddrinfoPtr jsocketpp::ServerSocket::_srvAddrInfo = nullptr
private

Address info for binding (from getaddrinfo).


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