This is an example for a very simple TCP client application. IT connects to a server, blocking until connected and reads available data until the read times out.
Output when the TCP_Server example is running:
Using server: 127.0.0.1
Received data from server: The quick brown fox jumps over the lazy dog
#include <array>
#include <iostream>
int main()
{
try {
std::cout << "Using server: " << server_ip << "\n";
auto res = client_socket.
connect(server_ip, 47777);
{
std::cerr << "Unable to connect to server\n";
return 1;
}
std::array<char, 256> buffer{};
while(true)
{
{
std::cout << "Received data from server: ";
std::cout.write(buffer.data(), result.
bytes);
std::cout << std::endl;
continue;
}
{
break;
}
std::cerr << "\nTimed out waiting for server data.\n";
return 1;
}
return 0;
}
{
std::cerr << e.
what() << std::endl;
return 1;
}
}
ConnectResult connect(std::string_view foreignAddress, unsigned short foreignPort)
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
std::string resolveHostname(const std::string &hostname)