|
| | 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).
|
| ServerSocket & | operator= (const ServerSocket &rhs)=delete |
| | Copy assignment operator (deleted).
|
| | ServerSocket (ServerSocket &&rhs) noexcept |
| | Move constructor that transfers ownership of server socket resources.
|
| ServerSocket & | operator= (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< Socket > | 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 > | 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 | 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 > | 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 > | 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 | 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.
|
| | 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.
|
| SocketOptions & | operator= (const SocketOptions &)=delete |
| | Copy assignment operator (deleted) for SocketOptions.
|
| SocketOptions & | operator= (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.
|
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>
try {
server.bind();
server.listen();
std::cout << "Server is listening on port 12345..." << std::endl;
while (true) {
Socket client = server.accept();
std::cout << "Accepted connection from " << remoteAddr << std::endl;
std::string message = client.
read<std::string>();
}
} 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