|
| 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).
|
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 |
| 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< 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) const |
| Attempt to accept an incoming client connection, returning immediately or after the configured timeout.
|
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) 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< 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) const |
| Attempt to accept a client connection in non-blocking fashion.
|
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) 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.
|
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: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