This is an example for a very simple TCP client application.
Output when started without a server running: "Connection Refused"
Output when the TCP_Server example is running:
Received data from server: The quick brown fox jumps over the lazy dog
#include <simple_socket/TCPSocket.h>
#include <array>
#include <iostream>
int main()
{
try {
client_socket.
connect(
"127.0.0.1", 47777);
std::array<char, 256> buffer{};
std::cout << "Received data from server: ";
while(true)
{
int received = client_socket.
timedReceive(buffer.data(), buffer.size(), 5000);
if (received > 0)
{
std::cout.write(buffer.data(), received);
continue;
}
{
break;
}
std::cerr << "\nTimed out waiting for server data." << std::endl;
return 1;
}
std::cout << std::endl;
}
{
std::cerr << e.
what() << std::endl;
return 1;
}
return 0;
}
void connect(std::string_view foreignAddress, unsigned short foreignPort)
establish a connection with the given foreign address and port
int timedReceive(void *buffer, size_t len, int timeout)
receive data from a bound socket, return after the given timespan
bool peerDisconnected() const noexcept
returns whether a currently associated peer disconnected
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.