165 int soRecvTimeoutMillis = -1,
int soSendTimeoutMillis = -1,
bool tcpNoDelay =
true,
bool keepAlive =
false,
166 bool nonBlocking =
false);
268 Socket(std::string_view host,
Port port, std::optional<std::size_t> recvBufferSize = std::nullopt,
269 std::optional<std::size_t> sendBufferSize = std::nullopt,
270 std::optional<std::size_t> internalBufferSize = std::nullopt,
bool reuseAddress =
true,
271 int soRecvTimeoutMillis = -1,
int soSendTimeoutMillis = -1,
bool dualStack =
true,
bool tcpNoDelay =
true,
272 bool keepAlive =
false,
bool nonBlocking =
false,
bool autoConnect =
true,
bool autoBind =
false,
273 std::string_view localAddress =
"",
Port localPort = 0);
337 rhs._selectedAddrInfo =
nullptr;
338 rhs._isBound =
false;
339 rhs._isConnected =
false;
340 rhs.resetShutdownFlags();
431 rhs._selectedAddrInfo =
nullptr;
432 rhs._isBound =
false;
433 rhs._isConnected =
false;
434 rhs.resetShutdownFlags();
486 void bind(std::string_view localHost,
Port port);
604 [[nodiscard]] std::string
getLocalIp(
bool convertIPv4Mapped =
true)
const;
724 [[nodiscard]] std::string
getRemoteIp(
bool convertIPv4Mapped =
true)
const;
871 void connect(
int timeoutMillis = -1);
947 template <
typename T> [[nodiscard]] T
read()
949 static_assert(std::is_trivially_copyable_v<T>,
"Socket::read<T>() requires a trivially copyable type");
950 static_assert(std::is_standard_layout_v<T>,
"Socket::read<T>() requires a standard layout type");
952 std::array<std::byte,
sizeof(T)> buffer{};
953 std::size_t totalRead = 0;
954 std::size_t remaining =
sizeof(T);
956 while (remaining > 0)
958 const auto len = ::recv(
getSocketFd(),
reinterpret_cast<char*
>(buffer.data()) + totalRead,
960 static_cast<int>(remaining),
973 throw SocketException(
"Connection closed by remote host before full object was received.");
975 totalRead +=
static_cast<std::size_t
>(len);
976 remaining -=
static_cast<std::size_t
>(len);
979 return std::bit_cast<T>(buffer);
1038 std::string
readExact(std::size_t n)
const;
1098 std::string
readUntil(
char delimiter, std::size_t maxLen = 8192,
bool includeDelimiter =
true);
1129 std::string
readLine(
const std::size_t maxLen = 8192,
const bool includeDelimiter =
true)
1131 return readUntil(
'\n', maxLen, includeDelimiter);
1413 static_assert(std::is_integral_v<T> && std::is_unsigned_v<T> && std::is_trivially_copyable_v<T>,
1414 "Prefix type must be a trivially copyable unsigned integral type");
1418 return readExact(
static_cast<std::size_t
>(length));
1484 template <
typename T> std::string
readPrefixed(
const std::size_t maxPayloadLen)
1486 static_assert(std::is_integral_v<T> && std::is_trivially_copyable_v<T>,
1487 "Prefix type must be a trivially copyable integral type");
1492 const auto payloadLen =
static_cast<std::size_t
>(length);
1493 if (payloadLen > maxPayloadLen)
1495 throw SocketException(
"readPrefixed: Prefix length " + std::to_string(payloadLen) +
1496 " exceeds maximum allowed payload length of " + std::to_string(maxPayloadLen));
1629 std::size_t
readv(std::span<BufferView> buffers)
const;
1662 std::size_t
readvAll(std::span<BufferView> buffers)
const;
1808 std::string
peek(std::size_t n)
const;
1833 void discard(std::size_t n, std::size_t chunkSize = 1024)
const;
1999 [[nodiscard]] std::size_t
write(std::string_view message)
const;
2055 std::size_t
writeAll(std::string_view message)
const;
2115 static_assert(std::is_integral_v<T> && std::is_trivially_copyable_v<T>,
2116 "Prefix type must be a trivially copyable integral type");
2118 const std::size_t payloadSize = payload.size();
2126 if (payloadSize >
static_cast<std::size_t
>((std::numeric_limits<T>::max)()))
2128 throw SocketException(
"writePrefixed: Payload size " + std::to_string(payloadSize) +
2129 " exceeds maximum encodable size for prefix type");
2136 std::array<char,
sizeof(T)> prefixBuffer{};
2137 std::memcpy(prefixBuffer.data(), &len,
sizeof(T));
2138 const std::string_view prefixView(prefixBuffer.data(),
sizeof(T));
2141 const std::size_t prefixSent =
writeAll(prefixView);
2144 const std::size_t dataSent =
writeAll(payload);
2146 return prefixSent + dataSent;
2201 template <
typename T> std::size_t
writePrefixed(
const void* data, std::size_t len)
const
2203 static_assert(std::is_integral_v<T> && std::is_trivially_copyable_v<T>,
2204 "Prefix type must be a trivially copyable integral type");
2207 if (!data && len > 0)
2209 throw SocketException(
"writePrefixed: Null data pointer with non-zero length");
2213 if (len >
static_cast<std::size_t
>((std::numeric_limits<T>::max)()))
2215 throw SocketException(
"writePrefixed: Payload length " + std::to_string(len) +
2216 " exceeds capacity of prefix type (" +
2217 std::to_string((std::numeric_limits<T>::max)()) +
")");
2224 std::array<char,
sizeof(T)> prefixBuffer{};
2225 std::memcpy(prefixBuffer.data(), &prefix,
sizeof(T));
2226 const std::string_view prefixView(prefixBuffer.data(),
sizeof(T));
2229 const std::size_t prefixSent =
writeAll(prefixView);
2232 std::size_t payloadSent = 0;
2235 payloadSent =
writeAll(std::string_view(
static_cast<const char*
>(data), len));
2238 return prefixSent + payloadSent;
2278 std::size_t
writev(std::span<const std::string_view> buffers)
const;
2316 std::size_t
writevAll(std::span<const std::string_view> buffers)
const;
2403 std::size_t
writeFrom(
const void* data, std::size_t len)
const;
2435 std::size_t
writeFromAll(
const void* data, std::size_t len)
const;
2582 std::size_t
writevFrom(std::span<const BufferView> buffers)
const;
2618 std::size_t
writevFromAll(std::span<BufferView> buffers)
const;
2820 bool waitReady(
bool forWrite,
int timeoutMillis)
const;
2970 std::size_t
readIntoInternal(
void* buffer, std::size_t len,
bool exact =
false)
const;
Represents a raw writable memory region for scatter/gather I/O.
Exception class for socket-related errors in jsocketpp.
Defines the SocketOptions base class for cross-platform socket option access.
Represents socket-related errors in the jsocketpp library.
Definition SocketException.hpp:63
std::vector< char > _internalBuffer
Internal buffer for read operations, not thread-safe.
Definition Socket.hpp:3135
internal::AddrinfoPtr _cliAddrInfo
Address info for connection (from getaddrinfo).
Definition Socket.hpp:3133
bool _inputShutdown
True if input side is shutdown (recv disabled).
Definition Socket.hpp:3138
bool _outputShutdown
True if output side is shutdown (send disabled).
Definition Socket.hpp:3139
socklen_t _remoteAddrLen
Length of remote address (for recvfrom/recvmsg).
Definition Socket.hpp:3132
bool _isConnected
True if the socket is connected to a remote peer.
Definition Socket.hpp:3137
addrinfo * _selectedAddrInfo
Selected address info for connection.
Definition Socket.hpp:3134
bool _isBound
True if the socket is bound to an address.
Definition Socket.hpp:3136
sockaddr_storage _remoteAddr
(portability)
Definition Socket.hpp:3130
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 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
Socket & operator=(Socket &&rhs) noexcept
Move assignment operator that transfers socket ownership safely.
Definition Socket.hpp:404
friend class ServerSocket
Grants ServerSocket access to private members.
Definition Socket.hpp:107
std::size_t writeAtMostWithTimeout(std::string_view data, int timeoutMillis) const
Performs a best-effort write with a total timeout.
Definition Socket.cpp:967
std::string readLine(const std::size_t maxLen=8192, const bool includeDelimiter=true)
Reads a line terminated by ' ' from the socket.
Definition Socket.hpp:1129
std::string getRemoteIp(bool convertIPv4Mapped=true) const
Retrieves the IP address of the remote peer this TCP socket is connected to.
Definition Socket.cpp:379
Port getRemotePort() const
Retrieves the port number of the remote peer this TCP socket is connected to.
Definition Socket.cpp:396
bool isClosed() const noexcept
Reports whether the socket has been closed or invalidated.
Definition Socket.hpp:2850
std::string readAtMostWithTimeout(std::size_t n, int timeoutMillis) const
Attempts a best-effort read of up to n bytes with a timeout constraint.
Definition Socket.cpp:669
std::string readExact(std::size_t n) const
Reads exactly n bytes from the socket into a std::string.
Definition Socket.cpp:506
std::size_t writevFromWithTotalTimeout(std::span< BufferView > buffers, int timeoutMillis) const
Writes all raw memory buffers fully within a timeout using scatter I/O.
Definition Socket.cpp:1406
void setInternalBufferSize(std::size_t newLen)
Sets the size of the internal read buffer used for string operations.
Definition Socket.cpp:456
bool isInputShutdown() const noexcept
Checks whether the socket's input stream has been shutdown.
Definition Socket.hpp:2877
void resetShutdownFlags() noexcept
Resets internal shutdown state flags to false.
Definition Socket.hpp:3123
std::string readUntil(char delimiter, std::size_t maxLen=8192, bool includeDelimiter=true)
Reads data from the socket until a specified delimiter character is encountered.
Definition Socket.cpp:542
Socket & operator=(const Socket &rhs)=delete
Copy assignment operator (deleted) for Socket class.
std::string peek(std::size_t n) const
Peeks at incoming data without consuming it.
Definition Socket.cpp:799
std::size_t writevFrom(std::span< const BufferView > buffers) const
Writes multiple raw memory regions using vectorized I/O.
Definition Socket.cpp:1327
std::size_t writeFromAll(const void *data, std::size_t len) const
Writes all bytes from a raw memory buffer, retrying until complete.
Definition Socket.cpp:1028
std::size_t readvAtMostWithTimeout(std::span< BufferView > buffers, int timeoutMillis) const
Attempts a single vectorized read into multiple buffers with a timeout.
Definition Socket.cpp:1313
bool waitReady(bool forWrite, int timeoutMillis) const
Waits for the socket to become ready for reading or writing.
Definition Socket.cpp:462
std::string getLocalIp(bool convertIPv4Mapped=true) const
Retrieves the local IP address this socket is bound to.
Definition Socket.cpp:340
Socket(SOCKET client, const sockaddr_storage &addr, socklen_t len, std::size_t recvBufferSize=DefaultBufferSize, std::size_t sendBufferSize=DefaultBufferSize, std::size_t internalBufferSize=DefaultBufferSize, int soRecvTimeoutMillis=-1, int soSendTimeoutMillis=-1, bool tcpNoDelay=true, bool keepAlive=false, bool nonBlocking=false)
Wraps an accepted TCP client socket with optional tuning parameters.
Definition Socket.cpp:12
void cleanup()
Internal helper that closes the socket and clears address resolution state.
Definition Socket.cpp:98
void discard(std::size_t n, std::size_t chunkSize=1024) const
Discards exactly n bytes from the socket by reading and discarding them.
Definition Socket.cpp:831
std::size_t readIntoInternal(void *buffer, std::size_t len, bool exact=false) const
Reads data from the socket into a user-supplied buffer.
Definition Socket.cpp:632
void close()
Closes the socket connection and releases associated resources.
Definition Socket.cpp:282
std::string readAvailable() const
Reads all bytes currently available on the socket without blocking.
Definition Socket.cpp:702
std::size_t writevFromAll(std::span< BufferView > buffers) const
Writes all raw memory regions fully using scatter/gather I/O.
Definition Socket.cpp:1363
std::string readAtMost(std::size_t n) const
Performs a single best-effort read of up to n bytes from the socket.
Definition Socket.cpp:599
std::size_t writevAll(std::span< const std::string_view > buffers) const
Writes all buffers fully using vectorized I/O with automatic retry on partial sends.
Definition Socket.cpp:925
std::size_t writePrefixed(const std::string_view payload)
Writes a length-prefixed payload using a fixed-size integral prefix.
Definition Socket.hpp:2113
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
void cleanupAndRethrow()
Cleans up socket resources and rethrows the currently active exception.
Definition Socket.cpp:115
std::size_t writevWithTotalTimeout(std::span< const std::string_view > buffers, int timeoutMillis) const
Writes all buffers fully within a total timeout using vectorized I/O.
Definition Socket.cpp:1114
std::size_t readv(std::span< BufferView > buffers) const
Performs a vectorized read into multiple buffers using a single system call.
Definition Socket.cpp:1170
std::string getRemoteSocketAddress(bool convertIPv4Mapped=true) const
Get the connected peer's socket address as a formatted string.
Definition Socket.cpp:413
void connect(int timeoutMillis=-1)
Establishes a TCP connection to the remote host with optional timeout control.
Definition Socket.cpp:165
std::size_t writeWithTotalTimeout(std::string_view data, int timeoutMillis) const
Writes the full payload with a total timeout across all retries.
Definition Socket.cpp:1065
T read()
Reads a fixed-size, trivially copyable object of type T from the socket.
Definition Socket.hpp:947
void shutdown(ShutdownMode how) const
Shutdown specific communication aspects of the socket.
Definition Socket.cpp:293
std::size_t writePrefixed(const void *data, std::size_t len) const
Writes a binary payload prefixed with its length using a fixed-size integer type.
Definition Socket.hpp:2201
std::string readPrefixed()
Reads a length-prefixed payload using a fixed-size prefix type.
Definition Socket.hpp:1411
bool isConnected() const noexcept
Indicates whether the socket has been successfully connected to a remote host.
Definition Socket.hpp:562
std::size_t writeFrom(const void *data, std::size_t len) const
Writes up to len bytes from a raw memory buffer in a single send call.
Definition Socket.cpp:998
std::string getLocalSocketAddress(bool convertIPv4Mapped=true) const
Retrieves the full local socket address in the form "IP:port".
Definition Socket.cpp:374
std::size_t readIntoExact(void *buffer, const std::size_t len) const
Reads exactly len bytes into the given buffer (looped recv).
Definition Socket.hpp:1281
Socket()=delete
Default constructor (deleted) for Socket class.
Port getLocalPort() const
Retrieves the local port number this socket is bound to.
Definition Socket.cpp:357
std::size_t readIntoAvailable(void *buffer, std::size_t bufferSize) const
Reads all currently available bytes into the provided buffer without blocking.
Definition Socket.cpp:750
std::size_t readInto(void *buffer, const std::size_t len) const
Reads available data from the socket into the provided buffer.
Definition Socket.hpp:1228
std::string readPrefixed(const std::size_t maxPayloadLen)
Reads a length-prefixed message with an upper bound check.
Definition Socket.hpp:1484
bool isBound() const noexcept
Indicates whether the socket has been explicitly bound to a local address and/or port.
Definition Socket.hpp:535
void bind()
Binds the client socket to all interfaces using an ephemeral port.
Definition Socket.cpp:160
Socket(Socket &&rhs) noexcept
Move constructor that transfers ownership of socket resources.
Definition Socket.hpp:330
std::size_t writeAll(std::string_view message) const
Writes the entire contents of a message to the socket, retrying as needed.
Definition Socket.cpp:443
bool isOutputShutdown() const noexcept
Checks whether the socket's output stream has been shutdown.
Definition Socket.hpp:2903
std::size_t readvAll(std::span< BufferView > buffers) const
Reads exactly the full contents of all provided buffers.
Definition Socket.cpp:1211
std::size_t writev(std::span< const std::string_view > buffers) const
Writes multiple buffers in a single system call using scatter/gather I/O.
Definition Socket.cpp:872
bool isValid() const noexcept
Check if the socket is valid and open for communication.
Definition Socket.hpp:2756
std::size_t readvAllWithTotalTimeout(std::span< BufferView > buffers, int timeoutMillis) const
Reads exactly the full contents of all buffers within a timeout.
Definition Socket.cpp:1256
Socket(const Socket &rhs)=delete
Copy constructor (deleted) for Socket class.
void cleanupAndThrow(int errorCode)
Closes the socket, resets internal state, and throws a SocketException.
Definition Socket.cpp:109
~Socket() noexcept override
Destructs the Socket object, closing connections and freeing resources.
Definition Socket.cpp:264
uint16_t toNetwork(const uint16_t val)
Converts a 16-bit unsigned integer from host to network byte order.
Definition common.hpp:728
uint16_t fromNetwork(const uint16_t val)
Converts a 16-bit unsigned integer from network to host byte order.
Definition common.hpp:744
A C++ socket library providing Java-style networking interfaces.
Definition BufferView.hpp:16
ShutdownMode
Enum for socket shutdown modes.
Definition common.hpp:369
std::string SocketErrorMessage(int error, bool gaiStrerror=false)
Convert a socket-related error code to a human-readable message.
Definition common.cpp:5
constexpr SOCKET INVALID_SOCKET
Definition common.hpp:264
int GetSocketError()
Definition common.hpp:246
int SOCKET
Definition common.hpp:263
constexpr SOCKET SOCKET_ERROR
Definition common.hpp:265