simple-socket library 1.9.0
Loading...
Searching...
No Matches
TCP_Client_Reconnect.cpp

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)
{
// Use a fresh socket for every connection attempt
// Attempt to connect within 5s timeout
const auto connection = socket.timedConnect("127.0.0.1", 47777, 5000);
if (connection != NET::ConnectResult::Connected)
{
std::cerr << "Connect failed\n";
std::this_thread::sleep_for(3s);
continue;
}
std::cout << "Connected to "
<< socket.getForeignAddress() << ":"
<< socket.getForeignPort() << "\n";
std::array<char, 8192> buffer;
while(true)
{
// Expect to recevie initial data after at least 2s
const auto result = socket.timedReceive(buffer.data(), buffer.size(), 2000);
if (result.status == NET::IOStatus::Success)
{
std::cout << "Received data from server: ";
// Received network data is not necessarily null terminated
std::cout.write(buffer.data(), result.bytes);
std::cout << std::endl;
continue;
}
else if (result.status == NET::IOStatus::PeerDisconnected)
{
std::cerr << "Server disconnected; reconnecting\n";
break;
}
else
{
// No data within the deadline, or another error
std::cerr << "Receive timeout; reconnecting\n";
break;
}
}
std::this_thread::sleep_for(1s);
// socket destructor closes the connection here
}
}
catch (const NET::SocketException& e)
{
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.
TCP socket class.
Definition TCPSocket.h:11
@ Connected
the connection is established