A more advanced TCP client exmaple with reconection logic and full error handling. Demonstrates usability of real-world reconnect logic without an separate even loop.
Output when the TCP_Server example is running:
Connect failed
Connected to 127.0.0.1:47777
Received data from server: The quick brown fox jumps over the lazy dog
Server disconnected; reconnecting
#include <array>
#include <chrono>
#include <thread>
#include <iostream>
using namespace std::chrono_literals;
int main()
{
try {
while(true)
{
const auto connection = socket.
timedConnect(
"127.0.0.1", 47777, 5000);
{
std::cerr << "Connect failed\n";
std::this_thread::sleep_for(3s);
continue;
}
std::cout << "Connected to "
std::array<char, 8192> buffer;
while(true)
{
const auto result = socket.
timedReceive(buffer.data(), buffer.size(), 2000);
{
std::cout << "Received data from server: ";
std::cout.write(buffer.data(), result.bytes);
std::cout << std::endl;
continue;
}
{
std::cerr << "Server disconnected; reconnecting\n";
break;
}
else
{
std::cerr << "Receive timeout; reconnecting\n";
break;
}
}
std::this_thread::sleep_for(1s);
}
}
{
std::cerr <<
"Socket error: " << e.
what() <<
'\n';
return 1;
}
}
std::string getForeignAddress() const
unsigned short getForeignPort() const
ConnectResult timedConnect(std::string_view foreignAddress, unsigned short foreignPort, int timeout)
establish a connection with the given foreign address and port
IOResult timedReceive(void *buffer, size_t len, int timeout)
receive data from a bound socket, return after the given timespan
Signals a problem with the execution of a socket call.
const char * what() const noexcept
Returns a C-string describing the cause of the current error.
@ Connected
the connection is established