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>

Public Member Functions

 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 getInetAddress () const
 Get the local IP address to which the server socket is bound.
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
 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) const
 Accept an incoming client connection, respecting the configured socket timeout.
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) const
 Accept an incoming client connection, waiting up to the specified timeout.
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) const
 Attempt to accept an incoming client connection, returning immediately or after the configured timeout.
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) const
 Attempt to accept an incoming client connection, waiting up to a specified 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) const
 Accept an incoming client connection, always blocking until a client connects (unless the socket is set to non-blocking).
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) const
 Attempt to accept a client connection in non-blocking fashion.
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) const
 Asynchronously accept an incoming client connection, returning a future.
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) const
 Asynchronously accept a client connection and invoke a callback upon completion.
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.
void setOption (int level, int optName, int value)
 Set a socket option for the listening server socket.
int getOption (int level, int optName) const
 Retrieve the current value of a socket option for the listening server socket.
void setReuseAddress (bool enable)
 Enable or disable address reuse for this server socket.
bool getReuseAddress () const
 Query whether the address reuse option is enabled on this server socket.
void setNonBlocking (bool nonBlocking)
 Set the server socket to non-blocking or blocking mode.
bool getNonBlocking () const
 Check if the server socket is in non-blocking mode.
bool waitReady (std::optional< int > timeoutMillis=std::nullopt) const
 Wait 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 setIPv6Only (bool enable)
 Enable or disable IPv6-only mode for this server socket.
bool getIPv6Only () const
 Query whether IPv6-only mode is enabled.
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.
void setReusePort (bool enable)
 Enable or disable the SO_REUSEPORT socket option.
bool getReusePort () const
 Query whether SO_REUSEPORT is enabled for this socket.
SOCKET getHandle () const
 Get the underlying native socket handle/descriptor.

Static Public Member Functions

static int getSocketReuseOption ()
 Returns the correct socket option constant for address reuse, depending on the platform.

Protected Member Functions

void cleanupAndThrow (int errorCode)
 Cleans up server socket resources and throws a SocketException.

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 (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

SOCKET _serverSocket = INVALID_SOCKET
 Underlying socket file descriptor.
addrinfo * _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.

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:91
int main()
Definition client.cpp:89
size_t write(std::string_view message) const
Writes data to the socket, handling partial writes.
Definition Socket.cpp:279
std::string getRemoteSocketAddress(bool convertIPv4Mapped=true) const
Get the remote peer's address and port as a formatted string.
Definition Socket.cpp:243
T read()
Reads a fixed-size trivially copyable value of type T from the socket.
Definition Socket.hpp:553
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.
Definition ServerSocket.cpp:8

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 Data Documentation

◆ _defaultInternalBufferSize

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

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.

◆ _serverSocket

SOCKET jsocketpp::ServerSocket::_serverSocket = INVALID_SOCKET
private

Underlying socket file descriptor.

◆ _soTimeoutMillis

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

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

◆ _srvAddrInfo

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

Address info for binding (from getaddrinfo)


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