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

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 {
const std::string server_ip = NET::resolveHostname("localhost");
std::cout << "Using server: " << server_ip << "\n";
NET::TCPSocket client_socket;
// Connect to local TCP Server example
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)
{
// Wait for some data but bail out after some time
NET::IOResult result = client_socket.timedReceive(buffer.data(), buffer.size(), 5000);
{
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;
}
{
// Graceful EOF from the server
break;
}
std::cerr << "\nTimed out waiting for server data.\n";
return 1;
}
// No explicit close is necessary
return 0;
}
catch (const NET::SocketException& e)
{
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.
TCP socket class.
Definition TCPSocket.h:11
@ Connected
the connection is established
std::string resolveHostname(const std::string &hostname)
IOStatus status