|
| Socket ()=delete |
| Default constructor (deleted) for Socket class.
|
| Socket (std::string_view host, Port port, std::optional< std::size_t > recvBufferSize=std::nullopt, std::optional< std::size_t > sendBufferSize=std::nullopt, std::optional< std::size_t > internalBufferSize=std::nullopt) |
| Creates a new Socket object configured to connect to the specified host and port.
|
| Socket (const Socket &rhs)=delete |
| Copy constructor (deleted) for Socket class.
|
| Socket (Socket &&rhs) noexcept |
| Move constructor that transfers ownership of socket resources.
|
Socket & | operator= (const Socket &rhs)=delete |
| Copy assignment operator (deleted) for Socket class.
|
Socket & | operator= (Socket &&rhs) noexcept |
| Move assignment operator that transfers socket ownership safely.
|
| ~Socket () noexcept |
| Destructs the Socket object, closing connections and freeing resources.
|
std::string | getRemoteSocketAddress (bool convertIPv4Mapped=true) const |
| Get the remote peer's address and port as a formatted string.
|
void | connect (int timeoutMillis=-1) const |
| Establishes a TCP connection to the remote host with optional timeout control.
|
template<typename T> |
T | read () |
| Reads a fixed-size trivially copyable value of type T from the socket.
|
std::string | readExact (std::size_t n) const |
| Read exactly n bytes from the socket into a string.
|
std::string | readUntil (char delimiter, std::size_t maxLen=8192, bool includeDelimiter=true) const |
| Reads data from the socket until a specified delimiter character.
|
std::string | readLine (const std::size_t maxLen=8192, const bool includeDelimiter=true) const |
| Reads a line terminated by '
' from the socket.
|
std::string | readAtMost (std::size_t n) const |
| Reads up to n bytes from the socket into a string.
|
std::size_t | readInto (void *buffer, const std::size_t len) const |
| Reads available data from the socket into the provided buffer.
|
std::size_t | readIntoExact (void *buffer, const std::size_t len) const |
| Reads exactly len bytes into the given buffer (looped recv).
|
std::string | readAtMostWithTimeout (std::size_t n, int timeoutMillis) const |
| Performs a best-effort read up to n bytes, with a maximum timeout.
|
template<typename T> |
std::string | readPrefixed () |
| Reads a length-prefixed payload using a fixed-size prefix type.
|
template<typename T> |
std::string | readPrefixed (const std::size_t maxPayloadLen) |
| Reads a length-prefixed message with an upper bound check.
|
std::string | readAvailable () const |
| Reads all bytes currently available on the socket without blocking.
|
std::size_t | readIntoAvailable (void *buffer, std::size_t bufferSize) const |
| Reads all currently available bytes into the provided buffer without blocking.
|
std::size_t | readv (std::span< BufferView > buffers) const |
| Performs a vectorized read into multiple buffers using a single system call.
|
std::size_t | readvAll (std::span< BufferView > buffers) const |
| Reads exactly the full contents of all provided buffers.
|
std::size_t | readvAllWithTotalTimeout (std::span< BufferView > buffers, int timeoutMillis) const |
| Reads exactly the full contents of all buffers within a timeout.
|
std::size_t | readvAtMostWithTimeout (std::span< BufferView > buffers, int timeoutMillis) const |
| Attempts a single vectorized read into multiple buffers with a timeout.
|
std::string | peek (std::size_t n) const |
| Peeks at incoming data without consuming it.
|
void | discard (std::size_t n, std::size_t chunkSize=1024) const |
| Discards exactly n bytes from the socket by reading and discarding them.
|
void | close () |
| Closes the socket connection and releases associated resources.
|
void | shutdown (ShutdownMode how) const |
| Shutdown specific communication aspects of the socket.
|
size_t | write (std::string_view message) const |
| Writes data to the socket, handling partial writes.
|
size_t | writeAll (std::string_view message) const |
| Writes the entire contents of a message to the socket, handling partial writes.
|
template<typename T> |
std::size_t | writePrefixed (const std::string &payload) |
| Writes a length-prefixed payload using a fixed-size prefix type.
|
template<typename T> |
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.
|
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.
|
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.
|
std::size_t | writeAtMostWithTimeout (std::string_view data, int timeoutMillis) const |
| Performs a best-effort write with a total timeout.
|
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.
|
std::size_t | writeFromAll (const void *data, std::size_t len) const |
| Writes all bytes from a raw memory buffer, retrying until complete.
|
std::size_t | writeWithTotalTimeout (std::string_view data, int timeoutMillis) const |
| Writes the full payload with a total timeout across all retries.
|
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.
|
std::size_t | writevFrom (std::span< const BufferView > buffers) const |
| Writes multiple raw memory regions using vectorized I/O.
|
std::size_t | writevFromAll (std::span< BufferView > buffers) const |
| Writes all raw memory regions fully using scatter/gather I/O.
|
std::size_t | writevFromWithTotalTimeout (std::span< BufferView > buffers, int timeoutMillis) const |
| Writes all raw memory buffers fully within a timeout using scatter I/O.
|
void | setReceiveBufferSize (std::size_t size) |
| Sets the socket's receive buffer size (SO_RCVBUF).
|
void | setSendBufferSize (std::size_t size) |
| Sets the socket's send buffer size (SO_SNDBUF).
|
int | getReceiveBufferSize () const |
| Get the socket's receive buffer size (SO_RCVBUF).
|
int | getSendBufferSize () const |
| Get the socket's send buffer size (SO_SNDBUF).
|
void | setInternalBufferSize (std::size_t newLen) |
| Sets the size of the internal read buffer used for string operations.
|
bool | isValid () const noexcept |
| Check if the socket is valid and open for communication.
|
void | setNonBlocking (bool nonBlocking) const |
| Set the socket to non-blocking or blocking mode.
|
bool | getNonBlocking () const |
| Check if the socket is currently in non-blocking mode.
|
void | setSoTimeout (int millis, bool forRead=true, bool forWrite=true) |
| Set timeout for socket send and/or receive operations.
|
bool | waitReady (bool forWrite, int timeoutMillis) const |
| Wait for the socket to be ready for reading or writing.
|
bool | isConnected () const |
| Check if the socket is still connected (TCP only).
|
void | enableNoDelay (bool enable) |
| Enable or disable TCP_NODELAY (Nagle's algorithm) on the socket.
|
void | enableKeepAlive (bool enable) |
| Enable or disable SO_KEEPALIVE on the socket.
|
void | setOption (int level, int optName, int value) |
| Set a socket option at the specified level.
|
int | getOption (int level, int optName) const |
| Get the current value of a socket option at the specified level.
|
template<> |
std::string | read () |
| Template specialization to read a string from the socket.
|
TCP client connection abstraction (Java-like interface).
The Socket class represents a TCP connection between your application and a remote host. It provides a high-level, easy-to-use, and cross-platform API for creating, connecting, sending, and receiving data over TCP sockets. Its interface is inspired by Java's Socket class, but uses modern C++20 features.
Key Features
- Connect to remote hosts using hostnames or IP addresses (IPv4/IPv6).
- Blocking or timeout-enabled connect for fine-grained control over connection attempts.
- Safe resource management: sockets are closed automatically when the object is destroyed.
- Read/write interface for sending and receiving binary data or text.
- Move-only: socket resources are never accidentally copied.
- Exception-based error handling via SocketException.
- Fine-grained control: configure timeouts, non-blocking mode, TCP_NODELAY, SO_KEEPALIVE, etc.
Typical Usage Example
#include <iostream>
try {
sock.connect(3000);
sock.write("GET / HTTP/1.0\r\n\r\n");
std::string response = sock.read<std::string>();
std::cout << "Received: " << response << std::endl;
sock.close();
std::cerr << "Socket error: " << ex.what() << std::endl;
}
}
TCP client socket abstraction for jsocketpp.
Represents socket-related errors in the jsocketpp library.
Definition SocketException.hpp:58
TCP client connection abstraction (Java-like interface).
Definition Socket.hpp:91
int main()
Definition client.cpp:89
Internal Buffer
Error Handling
- Almost all methods throw jsocketpp::SocketException on error (e.g., connect failure, write error, etc).
- You should catch exceptions to handle network errors gracefully.
Thread Safety
- Not thread-safe. Use a separate Socket object per thread if needed.
Platform Support
- Windows, Linux, macOS. Handles all necessary platform differences internally.
Advanced Usage
See Also