jsocketpp 1.0
A cross-platform C++20 socket library.
Loading...
Searching...
No Matches
ServerSocket.hpp
Go to the documentation of this file.
1
8
9#pragma once
10
11#include "common.hpp"
12#include "Socket.hpp"
13
14#include <exception>
15#include <functional>
16#include <future>
17#include <optional>
18
20
21namespace jsocketpp
22{
23
100{
101 public:
123 ServerSocket() = delete;
124
196 explicit ServerSocket(Port port, std::string_view localAddress = {}, bool autoBindListen = true,
197 bool reuseAddress = true, int soTimeoutMillis = -1, bool dualStack = true);
198
214 [[nodiscard]] std::string getLocalIp(bool convertIPv4Mapped = true) const;
215
237 [[nodiscard]] Port getLocalPort() const;
238
257 [[nodiscard]] std::string getLocalSocketAddress() const;
258
277 ServerSocket(const ServerSocket& rhs) = delete; //-Weffc++
278
297 ServerSocket& operator=(const ServerSocket& rhs) = delete; //-Weffc++
298
329 : SocketOptions(rhs.getSocketFd()), _srvAddrInfo(std::move(rhs._srvAddrInfo)),
330 _selectedAddrInfo(rhs._selectedAddrInfo), _port(rhs._port), _isBound(rhs._isBound),
331 _isListening(rhs._isListening), _soTimeoutMillis(rhs._soTimeoutMillis),
332 _defaultReceiveBufferSize(rhs._defaultReceiveBufferSize)
333 {
334 rhs.setSocketFd(INVALID_SOCKET);
335 rhs._selectedAddrInfo = nullptr;
336 rhs._isBound = false;
337 rhs._isListening = false;
338 }
339
368 {
369 if (this != &rhs)
370 {
371 // Clean up current socket
372 try
373 {
374 close(); // Clean up existing resources
375 }
376 catch (...)
377 {
378 }
379
380 // Transfer ownership
381 setSocketFd(rhs.getSocketFd());
382 _srvAddrInfo = std::move(rhs._srvAddrInfo);
383 _selectedAddrInfo = rhs._selectedAddrInfo;
384 _port = rhs._port;
385 _isBound = rhs._isBound;
386 _isListening = rhs._isListening;
387 _soTimeoutMillis = rhs._soTimeoutMillis;
388 _defaultReceiveBufferSize = rhs._defaultReceiveBufferSize;
389
390 // Reset source;
391 rhs.setSocketFd(INVALID_SOCKET);
392 rhs._selectedAddrInfo = nullptr;
393 rhs._isBound = false;
394 rhs._isListening = false;
395 }
396 return *this;
397 }
398
431 ~ServerSocket() noexcept override;
432
470 void bind();
471
484 [[nodiscard]] bool isBound() const noexcept { return _isBound; }
485
528 void listen(int backlog = 128);
529
542 [[nodiscard]] bool isListening() const noexcept { return _isListening; }
543
628 [[nodiscard]] Socket accept(std::optional<std::size_t> recvBufferSize = std::nullopt,
629 std::optional<std::size_t> sendBufferSize = std::nullopt,
630 std::optional<std::size_t> internalBufferSize = std::nullopt,
631 int soRecvTimeoutMillis = -1, int soSendTimeoutMillis = -1, bool tcpNoDelay = true,
632 bool keepAlive = false, bool nonBlocking = false) const;
633
722 [[nodiscard]] Socket accept(int timeoutMillis, std::optional<std::size_t> recvBufferSize = std::nullopt,
723 std::optional<std::size_t> sendBufferSize = std::nullopt,
724 std::optional<std::size_t> internalBufferSize = std::nullopt,
725 int soRecvTimeoutMillis = -1, int soSendTimeoutMillis = -1, bool tcpNoDelay = true,
726 bool keepAlive = false, bool nonBlocking = false) const;
727
812 [[nodiscard]] std::optional<Socket> tryAccept(std::optional<std::size_t> recvBufferSize = std::nullopt,
813 std::optional<std::size_t> sendBufferSize = std::nullopt,
814 std::optional<std::size_t> internalBufferSize = std::nullopt,
815 int soRecvTimeoutMillis = -1, int soSendTimeoutMillis = -1,
816 bool tcpNoDelay = true, bool keepAlive = false,
817 bool nonBlocking = false) const;
818
909 [[nodiscard]] std::optional<Socket> tryAccept(int timeoutMillis,
910 std::optional<std::size_t> recvBufferSize = std::nullopt,
911 std::optional<std::size_t> sendBufferSize = std::nullopt,
912 std::optional<std::size_t> internalBufferSize = std::nullopt,
913 int soRecvTimeoutMillis = -1, int soSendTimeoutMillis = -1,
914 bool tcpNoDelay = true, bool keepAlive = false,
915 bool nonBlocking = false) const;
916
1000 [[nodiscard]] Socket acceptBlocking(std::optional<std::size_t> recvBufferSize = std::nullopt,
1001 std::optional<std::size_t> sendBufferSize = std::nullopt,
1002 std::optional<std::size_t> internalBufferSize = std::nullopt,
1003 int soRecvTimeoutMillis = -1, int soSendTimeoutMillis = -1,
1004 bool tcpNoDelay = true, bool keepAlive = false, bool nonBlocking = false) const;
1005
1088 [[nodiscard]] std::optional<Socket> acceptNonBlocking(std::optional<std::size_t> recvBufferSize = std::nullopt,
1089 std::optional<std::size_t> sendBufferSize = std::nullopt,
1090 std::optional<std::size_t> internalBufferSize = std::nullopt,
1091 int soRecvTimeoutMillis = -1, int soSendTimeoutMillis = -1,
1092 bool tcpNoDelay = true, bool keepAlive = false,
1093 bool nonBlocking = false) const;
1094
1186 [[nodiscard]] std::future<Socket> acceptAsync(std::optional<std::size_t> recvBufferSize = std::nullopt,
1187 std::optional<std::size_t> sendBufferSize = std::nullopt,
1188 std::optional<std::size_t> internalBufferSize = std::nullopt,
1189 int soRecvTimeoutMillis = -1, int soSendTimeoutMillis = -1,
1190 bool tcpNoDelay = true, bool keepAlive = false,
1191 bool nonBlocking = false) const;
1192
1283 void acceptAsync(std::function<void(std::optional<Socket>, std::exception_ptr)> callback,
1284 std::optional<std::size_t> recvBufferSize = std::nullopt,
1285 std::optional<std::size_t> sendBufferSize = std::nullopt,
1286 std::optional<std::size_t> internalBufferSize = std::nullopt, int soRecvTimeoutMillis = -1,
1287 int soSendTimeoutMillis = -1, bool tcpNoDelay = true, bool keepAlive = false,
1288 bool nonBlocking = false) const;
1289
1324 void close();
1325
1342 [[nodiscard]] bool isValid() const noexcept { return getSocketFd() != INVALID_SOCKET; }
1343
1356 [[nodiscard]] bool isClosed() const noexcept { return getSocketFd() == INVALID_SOCKET; }
1357
1397 [[nodiscard]] bool waitReady(std::optional<int> timeoutMillis = std::nullopt) const;
1398
1423 void setSoTimeout(const int timeoutMillis) { _soTimeoutMillis = timeoutMillis; }
1424
1441 [[nodiscard]] int getSoTimeout() const noexcept { return _soTimeoutMillis; }
1442
1459 void setDefaultReceiveBufferSize(const std::size_t size) { _defaultReceiveBufferSize = size; }
1460
1474 [[nodiscard]] std::size_t getDefaultReceiveBufferSize() const noexcept { return _defaultReceiveBufferSize; }
1475
1492 void setDefaultSendBufferSize(const std::size_t size) { _defaultSendBufferSize = size; }
1493
1507 [[nodiscard]] std::size_t getDefaultSendBufferSize() const noexcept { return _defaultSendBufferSize; }
1508
1526 void setDefaultInternalBufferSize(const std::size_t size) { _defaultInternalBufferSize = size; }
1527
1545 [[nodiscard]] std::size_t getDefaultInternalBufferSize() const noexcept { return _defaultInternalBufferSize; }
1546
1547 protected:
1575 void cleanup();
1576
1604 void cleanupAndThrow(int errorCode);
1605
1636 void cleanupAndRethrow();
1637
1662 [[nodiscard]] bool isPassiveSocket() const noexcept override { return true; }
1663
1664 private:
1681 [[nodiscard]] std::size_t getEffectiveReceiveBufferSize(const std::optional<std::size_t> recvBufferSize) const
1682 {
1683 return recvBufferSize.value_or(_defaultReceiveBufferSize);
1684 }
1685
1702 [[nodiscard]] std::size_t getEffectiveSendBufferSize(std::optional<std::size_t> sendBufferSize) const
1703 {
1704 return sendBufferSize.value_or(_defaultSendBufferSize);
1705 }
1706
1728 [[nodiscard]] std::size_t getEffectiveInternalBufferSize(const std::optional<std::size_t> internalBufferSize) const
1729 {
1730 return internalBufferSize.value_or(_defaultInternalBufferSize);
1731 }
1732
1749 [[nodiscard]] std::tuple<std::size_t, std::size_t, std::size_t>
1750 resolveBuffers(const std::optional<std::size_t> recv, const std::optional<std::size_t> send,
1751 const std::optional<std::size_t> internal) const
1752 {
1755 }
1756
1758 addrinfo* _selectedAddrInfo = nullptr;
1760 bool _isBound = false;
1761 bool _isListening = false;
1768};
1769
1770} // namespace jsocketpp
TCP client socket abstraction for jsocketpp.
bool _isListening
True if the server socket is listening.
Definition ServerSocket.hpp:1761
Port _port
Port number the server will listen on.
Definition ServerSocket.hpp:1759
int _soTimeoutMillis
Timeout for accept(); -1 = no timeout, 0 = poll, >0 = timeout in milliseconds.
Definition ServerSocket.hpp:1762
std::size_t _defaultReceiveBufferSize
Default buffer size used for accepted client sockets when no specific size is provided.
Definition ServerSocket.hpp:1763
addrinfo * _selectedAddrInfo
Selected address info for binding.
Definition ServerSocket.hpp:1758
std::string getLocalIp(bool convertIPv4Mapped=true) const
Returns the local IP address this server socket is bound to.
Definition ServerSocket.cpp:141
std::size_t _defaultSendBufferSize
Default send buffer size for accepted client sockets.
Definition ServerSocket.hpp:1765
bool _isBound
True if the server socket is bound.
Definition ServerSocket.hpp:1760
internal::AddrinfoPtr _srvAddrInfo
Address info for binding (from getaddrinfo).
Definition ServerSocket.hpp:1757
std::size_t _defaultInternalBufferSize
Default internal buffer size for accepted client sockets, used by some read() methods.
Definition ServerSocket.hpp:1766
TCP client connection abstraction (Java-like interface).
Definition Socket.hpp:93
Common platform and utility includes for jsocketpp.
std::uint16_t Port
Type alias representing a TCP or UDP port number (1–65535).
Definition common.hpp:392
constexpr std::size_t DefaultBufferSize
Default internal buffer size (in bytes) for socket read operations.
Definition common.hpp:434
std::unique_ptr< addrinfo, AddrinfoDeleter > AddrinfoPtr
Smart pointer that manages addrinfo* resources using AddrinfoDeleter.
Definition common.hpp:819
void setSoTimeout(const int timeoutMillis)
Set the logical timeout (in milliseconds) for accepting client connections.
Definition ServerSocket.hpp:1423
int getSoTimeout() const noexcept
Get the logical timeout (in milliseconds) for accept operations.
Definition ServerSocket.hpp:1441
void setSocketFd(const SOCKET sock) noexcept
Updates the socket descriptor used by this object.
Definition SocketOptions.hpp:2281
SocketOptions()=delete
Default constructor (deleted) for SocketOptions base class.
SOCKET getSocketFd() const noexcept
Retrieves the native socket handle (file descriptor or OS-level handle).
Definition SocketOptions.hpp:275
bool isPassiveSocket() const noexcept override
Identifies this socket as a passive (listening) socket.
Definition ServerSocket.hpp:1662
void close()
Closes the server socket and releases its associated system resources.
Definition ServerSocket.cpp:211
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.
Definition ServerSocket.hpp:1750
~ServerSocket() noexcept override
Destructor that automatically closes the server socket and releases all associated resources.
Definition ServerSocket.cpp:197
bool isBound() const noexcept
Check if the server socket is bound to a local address.
Definition ServerSocket.hpp:484
std::size_t getEffectiveSendBufferSize(std::optional< std::size_t > sendBufferSize) const
Get the effective send buffer size to use for socket write operations.
Definition ServerSocket.hpp:1702
bool isListening() const noexcept
Check if the server socket is currently listening for incoming connections.
Definition ServerSocket.hpp:542
void bind()
Binds the server socket to the configured port and network interface.
Definition ServerSocket.cpp:221
std::size_t getDefaultReceiveBufferSize() const noexcept
Get the current default receive buffer size for accepted client sockets.
Definition ServerSocket.hpp:1474
void cleanup()
Cleans up internal resources and resets the server socket state.
Definition ServerSocket.cpp:119
void cleanupAndRethrow()
Cleans up internal resources and rethrows the current exception.
Definition ServerSocket.cpp:135
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.
Definition ServerSocket.hpp:1728
void listen(int backlog=128)
Marks the socket as a passive (listening) socket, ready to accept incoming TCP connection requests.
Definition ServerSocket.cpp:251
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.
Definition ServerSocket.cpp:338
bool isValid() const noexcept
Check whether the server socket is currently open and valid.
Definition ServerSocket.hpp:1342
ServerSocket()=delete
Default constructor (deleted) for ServerSocket class.
std::string getLocalSocketAddress() const
Get the local socket address (IP and port) to which the server socket is bound.
Definition ServerSocket.cpp:175
bool waitReady(std::optional< int > timeoutMillis=std::nullopt) const
Waits for the server socket to become ready to accept an incoming connection.
Definition ServerSocket.cpp:443
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 throwin...
Definition ServerSocket.cpp:300
std::size_t getDefaultSendBufferSize() const noexcept
Get the current default send buffer size for accepted client sockets.
Definition ServerSocket.hpp:1507
ServerSocket & operator=(const ServerSocket &rhs)=delete
Copy assignment operator (deleted).
ServerSocket & operator=(ServerSocket &&rhs) noexcept
Move assignment operator for ServerSocket.
Definition ServerSocket.hpp:367
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.
Definition ServerSocket.cpp:363
void setDefaultInternalBufferSize(const std::size_t size)
Set the per-instance default internal buffer size used for buffered read operations.
Definition ServerSocket.hpp:1526
void cleanupAndThrow(int errorCode)
Cleans up internal resources and throws a SocketException.
Definition ServerSocket.cpp:129
std::size_t getDefaultInternalBufferSize() const noexcept
Get the per-instance default internal buffer size used for buffered read operations.
Definition ServerSocket.hpp:1545
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 op...
Definition ServerSocket.cpp:262
ServerSocket(const ServerSocket &rhs)=delete
Copy constructor (deleted).
ServerSocket(ServerSocket &&rhs) noexcept
Move constructor that transfers ownership of server socket resources.
Definition ServerSocket.hpp:328
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 confi...
Definition ServerSocket.cpp:399
Port getLocalPort() const
Retrieve the local port number to which the server socket is bound.
Definition ServerSocket.cpp:158
void setDefaultSendBufferSize(const std::size_t size)
Set the default send buffer size for accepted client sockets.
Definition ServerSocket.hpp:1492
std::size_t getEffectiveReceiveBufferSize(const std::optional< std::size_t > recvBufferSize) const
Get the effective receive buffer size to use for socket read operations.
Definition ServerSocket.hpp:1681
bool isClosed() const noexcept
Check if the server socket has been closed.
Definition ServerSocket.hpp:1356
void setDefaultReceiveBufferSize(const std::size_t size)
Set the default receive buffer size for accepted client sockets.
Definition ServerSocket.hpp:1459
Implementation-only utilities and platform abstractions for jsocketpp.
Definition BufferView.hpp:52
A C++ socket library providing Java-style networking interfaces.
Definition BufferView.hpp:16
constexpr SOCKET INVALID_SOCKET
Definition common.hpp:264