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

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 {
NET::TCPSocket client_socket;
// Connect to local TCP Server example
client_socket.connect("127.0.0.1", 47777);
std::array<char, 256> buffer{};
std::cout << "Received data from server: ";
while(true)
{
// TCP is a byte stream: one receive call is not guaranteed
// to return everything the peer sent
int received = client_socket.timedReceive(buffer.data(), buffer.size(), 5000);
if (received > 0)
{
// Use the returned byte count
// Received network data is not necessarily null terminated
std::cout.write(buffer.data(), received);
continue;
}
if (client_socket.peerDisconnected())
{
// Graceful EOF from the server
break;
}
// timedReceive() also returns 0 when its timeout expires
std::cerr << "\nTimed out waiting for server data." << std::endl;
return 1;
}
std::cout << std::endl;
// No explicit close is necessary
}
catch (const NET::SocketException& e)
{
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.
TCP socket class.
Definition TCPSocket.h:11