jsocketpp 1.0
A cross-platform C++20 socket library.
Loading...
Searching...
No Matches
Socket.hpp
Go to the documentation of this file.
1
8
9#pragma once
10
11#include "BufferView.hpp"
12#include "common.hpp"
13#include "SocketException.hpp"
14#include "SocketOptions.hpp"
15
16#include <array>
17#include <bit>
18#include <limits>
19#include <optional>
20#include <span>
21#include <string_view>
22#include <type_traits>
23#include <vector>
24
26
27namespace jsocketpp
28{
29
92class Socket : public SocketOptions
93{
107 friend class ServerSocket;
108
109 protected:
163 Socket(SOCKET client, const sockaddr_storage& addr, socklen_t len, std::size_t recvBufferSize = DefaultBufferSize,
164 std::size_t sendBufferSize = DefaultBufferSize, std::size_t internalBufferSize = DefaultBufferSize,
165 int soRecvTimeoutMillis = -1, int soSendTimeoutMillis = -1, bool tcpNoDelay = true, bool keepAlive = false,
166 bool nonBlocking = false);
167
168 public:
190 Socket() = delete;
191
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);
274
300 Socket(const Socket& rhs) = delete; //-Weffc++
301
330 Socket(Socket&& rhs) noexcept
331 : SocketOptions(rhs.getSocketFd()), _remoteAddr(rhs._remoteAddr), _remoteAddrLen(rhs._remoteAddrLen),
332 _cliAddrInfo(std::move(rhs._cliAddrInfo)), _selectedAddrInfo(rhs._selectedAddrInfo),
333 _internalBuffer(std::move(rhs._internalBuffer)), _isBound(rhs._isBound), _isConnected(rhs._isConnected),
334 _inputShutdown(rhs._inputShutdown), _outputShutdown(rhs._outputShutdown)
335 {
336 rhs.setSocketFd(INVALID_SOCKET);
337 rhs._selectedAddrInfo = nullptr;
338 rhs._isBound = false;
339 rhs._isConnected = false;
340 rhs.resetShutdownFlags();
341 }
342
370 Socket& operator=(const Socket& rhs) = delete; //-Weffc++
371
404 Socket& operator=(Socket&& rhs) noexcept
405 {
406 if (this != &rhs)
407 {
408 // Clean up current socket
409 try
410 {
411 close(); // Clean up existing resources
412 }
413 catch (...)
414 {
415 }
416
417 // Transfer ownership
418 setSocketFd(rhs.getSocketFd());
419 _remoteAddr = rhs._remoteAddr;
420 _remoteAddrLen = rhs._remoteAddrLen;
421 _cliAddrInfo = std::move(rhs._cliAddrInfo);
422 _selectedAddrInfo = rhs._selectedAddrInfo;
423 _internalBuffer = std::move(rhs._internalBuffer);
424 _isBound = rhs._isBound;
425 _isConnected = rhs._isConnected;
426 _inputShutdown = rhs._inputShutdown;
427 _outputShutdown = rhs._outputShutdown;
428
429 // Reset source
430 rhs.setSocketFd(INVALID_SOCKET);
431 rhs._selectedAddrInfo = nullptr;
432 rhs._isBound = false;
433 rhs._isConnected = false;
434 rhs.resetShutdownFlags();
435 }
436 return *this;
437 }
438
458 ~Socket() noexcept override;
459
486 void bind(std::string_view localHost, Port port);
487
499 void bind(Port port);
500
510 void bind();
511
535 [[nodiscard]] bool isBound() const noexcept { return _isBound; }
536
562 [[nodiscard]] bool isConnected() const noexcept { return _isConnected; }
563
604 [[nodiscard]] std::string getLocalIp(bool convertIPv4Mapped = true) const;
605
642 [[nodiscard]] Port getLocalPort() const;
643
684 [[nodiscard]] std::string getLocalSocketAddress(bool convertIPv4Mapped = true) const;
685
724 [[nodiscard]] std::string getRemoteIp(bool convertIPv4Mapped = true) const;
725
757 [[nodiscard]] Port getRemotePort() const;
758
799 [[nodiscard]] std::string getRemoteSocketAddress(bool convertIPv4Mapped = true) const;
800
871 void connect(int timeoutMillis = -1);
872
947 template <typename T> [[nodiscard]] T read()
948 {
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");
951
952 std::array<std::byte, sizeof(T)> buffer{};
953 std::size_t totalRead = 0;
954 std::size_t remaining = sizeof(T);
955
956 while (remaining > 0)
957 {
958 const auto len = ::recv(getSocketFd(), reinterpret_cast<char*>(buffer.data()) + totalRead,
959#ifdef _WIN32
960 static_cast<int>(remaining),
961#else
962 remaining,
963#endif
964 0);
965
966 if (len == SOCKET_ERROR)
967 {
968 const int error = GetSocketError();
969 throw SocketException(error, SocketErrorMessage(error));
970 }
971
972 if (len == 0)
973 throw SocketException("Connection closed by remote host before full object was received.");
974
975 totalRead += static_cast<std::size_t>(len);
976 remaining -= static_cast<std::size_t>(len);
977 }
978
979 return std::bit_cast<T>(buffer);
980 }
981
1038 std::string readExact(std::size_t n) const;
1039
1098 std::string readUntil(char delimiter, std::size_t maxLen = 8192, bool includeDelimiter = true);
1099
1129 std::string readLine(const std::size_t maxLen = 8192, const bool includeDelimiter = true)
1130 {
1131 return readUntil('\n', maxLen, includeDelimiter);
1132 }
1133
1183 std::string readAtMost(std::size_t n) const;
1184
1228 std::size_t readInto(void* buffer, const std::size_t len) const { return readIntoInternal(buffer, len, false); }
1229
1281 std::size_t readIntoExact(void* buffer, const std::size_t len) const { return readIntoInternal(buffer, len, true); }
1282
1343 std::string readAtMostWithTimeout(std::size_t n, int timeoutMillis) const;
1344
1411 template <typename T> std::string readPrefixed()
1412 {
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");
1415
1416 T netLen = read<T>();
1417 T length = net::fromNetwork(netLen);
1418 return readExact(static_cast<std::size_t>(length));
1419 }
1420
1484 template <typename T> std::string readPrefixed(const std::size_t maxPayloadLen)
1485 {
1486 static_assert(std::is_integral_v<T> && std::is_trivially_copyable_v<T>,
1487 "Prefix type must be a trivially copyable integral type");
1488
1489 T netLen = read<T>();
1490 T length = net::fromNetwork(netLen);
1491
1492 const auto payloadLen = static_cast<std::size_t>(length);
1493 if (payloadLen > maxPayloadLen)
1494 {
1495 throw SocketException("readPrefixed: Prefix length " + std::to_string(payloadLen) +
1496 " exceeds maximum allowed payload length of " + std::to_string(maxPayloadLen));
1497 }
1498
1499 return readExact(payloadLen);
1500 }
1501
1548 std::string readAvailable() const;
1549
1594 std::size_t readIntoAvailable(void* buffer, std::size_t bufferSize) const;
1595
1629 std::size_t readv(std::span<BufferView> buffers) const;
1630
1662 std::size_t readvAll(std::span<BufferView> buffers) const;
1663
1713 std::size_t readvAllWithTotalTimeout(std::span<BufferView> buffers, int timeoutMillis) const;
1714
1768 std::size_t readvAtMostWithTimeout(std::span<BufferView> buffers, int timeoutMillis) const;
1769
1808 std::string peek(std::size_t n) const;
1809
1833 void discard(std::size_t n, std::size_t chunkSize = 1024) const;
1834
1873 void close();
1874
1943 void shutdown(ShutdownMode how) const;
1944
1999 [[nodiscard]] std::size_t write(std::string_view message) const;
2000
2055 std::size_t writeAll(std::string_view message) const;
2056
2113 template <typename T> std::size_t writePrefixed(const std::string_view payload)
2114 {
2115 static_assert(std::is_integral_v<T> && std::is_trivially_copyable_v<T>,
2116 "Prefix type must be a trivially copyable integral type");
2117
2118 const std::size_t payloadSize = payload.size();
2119
2120 // Guard against overflows: ensure payload fits in the prefix type
2121 // Note: Put parentheses around the `max` function name due to a collision with
2122 // a macro defined in windows.h. See:
2123 // https://stackoverflow.com/a/13420838/3049315
2124 // Another alternative would be to define `NOMINMAX` before including windows.h
2125 // such as in CMake when compiling the target library
2126 if (payloadSize > static_cast<std::size_t>((std::numeric_limits<T>::max)()))
2127 {
2128 throw SocketException("writePrefixed: Payload size " + std::to_string(payloadSize) +
2129 " exceeds maximum encodable size for prefix type");
2130 }
2131
2132 // Convert the length to network byte order
2133 T len = net::toNetwork(static_cast<T>(payloadSize));
2134
2135 // Copy the prefix value into a properly aligned buffer to avoid UB
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));
2139
2140 // Write the length prefix
2141 const std::size_t prefixSent = writeAll(prefixView);
2142
2143 // Then write the payload
2144 const std::size_t dataSent = writeAll(payload);
2145
2146 return prefixSent + dataSent;
2147 }
2148
2201 template <typename T> std::size_t writePrefixed(const void* data, std::size_t len) const
2202 {
2203 static_assert(std::is_integral_v<T> && std::is_trivially_copyable_v<T>,
2204 "Prefix type must be a trivially copyable integral type");
2205
2206 // Check for null pointer with non-zero length
2207 if (!data && len > 0)
2208 {
2209 throw SocketException("writePrefixed: Null data pointer with non-zero length");
2210 }
2211
2212 // Ensure the payload length fits in the prefix type
2213 if (len > static_cast<std::size_t>((std::numeric_limits<T>::max)()))
2214 {
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)()) + ")");
2218 }
2219
2220 // Encode prefix in network byte order
2221 T prefix = net::toNetwork(static_cast<T>(len));
2222
2223 // Use aligned buffer to avoid undefined behavior when casting to char*
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));
2227
2228 // Send prefix
2229 const std::size_t prefixSent = writeAll(prefixView);
2230
2231 // Send payload if any
2232 std::size_t payloadSent = 0;
2233 if (len > 0)
2234 {
2235 payloadSent = writeAll(std::string_view(static_cast<const char*>(data), len));
2236 }
2237
2238 return prefixSent + payloadSent;
2239 }
2240
2278 std::size_t writev(std::span<const std::string_view> buffers) const;
2279
2316 std::size_t writevAll(std::span<const std::string_view> buffers) const;
2317
2371 std::size_t writeAtMostWithTimeout(std::string_view data, int timeoutMillis) const;
2372
2403 std::size_t writeFrom(const void* data, std::size_t len) const;
2404
2435 std::size_t writeFromAll(const void* data, std::size_t len) const;
2436
2489 std::size_t writeWithTotalTimeout(std::string_view data, int timeoutMillis) const;
2490
2549 std::size_t writevWithTotalTimeout(std::span<const std::string_view> buffers, int timeoutMillis) const;
2550
2582 std::size_t writevFrom(std::span<const BufferView> buffers) const;
2583
2618 std::size_t writevFromAll(std::span<BufferView> buffers) const;
2619
2679 std::size_t writevFromWithTotalTimeout(std::span<BufferView> buffers, int timeoutMillis) const;
2680
2719 void setInternalBufferSize(std::size_t newLen);
2720
2756 [[nodiscard]] bool isValid() const noexcept { return getSocketFd() != INVALID_SOCKET; }
2757
2820 bool waitReady(bool forWrite, int timeoutMillis) const;
2821
2850 [[nodiscard]] bool isClosed() const noexcept { return getSocketFd() == INVALID_SOCKET; }
2851
2877 [[nodiscard]] bool isInputShutdown() const noexcept { return _inputShutdown; }
2878
2903 [[nodiscard]] bool isOutputShutdown() const noexcept { return _outputShutdown; }
2904
2905 protected:
2970 std::size_t readIntoInternal(void* buffer, std::size_t len, bool exact = false) const;
2971
3006 void cleanup();
3007
3050 void cleanupAndThrow(int errorCode);
3051
3098 void cleanupAndRethrow();
3099
3123 void resetShutdownFlags() noexcept
3124 {
3125 _inputShutdown = false;
3126 _outputShutdown = false;
3127 }
3128
3129 private:
3130 sockaddr_storage _remoteAddr;
3132 mutable socklen_t _remoteAddrLen = 0;
3134 addrinfo* _selectedAddrInfo = nullptr;
3135 std::vector<char> _internalBuffer;
3136 bool _isBound = false;
3137 bool _isConnected = false;
3138 bool _inputShutdown = false;
3139 bool _outputShutdown = false;
3140};
3141
3198template <> inline std::string Socket::read()
3199{
3200 const auto len = recv(getSocketFd(), _internalBuffer.data(),
3201#ifdef _WIN32
3202 static_cast<int>(_internalBuffer.size()),
3203#else
3204 _internalBuffer.size(),
3205#endif
3206 0);
3207 if (len == SOCKET_ERROR)
3208 {
3209 const int error = GetSocketError();
3210 throw SocketException(error, SocketErrorMessage(error));
3211 }
3212
3213 if (len == 0)
3214 throw SocketException("Connection closed by remote host.");
3215 return {_internalBuffer.data(), static_cast<size_t>(len)};
3216}
3217
3218} // namespace jsocketpp
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