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

This is an example for a very simple TCP server application. It waits for a clients, sends a fixed message and disconnect again. When nobody connects within 5s, the server shuts down.

Output when the TCP_Client is started:

Waiting for a client...
Client connected from 127.0.0.1:35296
Successfully sent 43 bytes.
Waiting for a client...
Timed out waiting for a client.
#include <iostream>
const char hello_msg[] = "The quick brown fox jumps over the lazy dog";
const size_t hello_len = sizeof(hello_msg) - 1;
int main()
{
try {
NET::TCPSocket server_socket;
// Allows server to bind again while stale connections are waiting
server_socket.setReuseAddress(true);
// Listen locally on the given port
server_socket.bind("127.0.0.1", 47777);
server_socket.listen();
while(true)
{
std::cout << "Waiting for a client...\n";
// Wait up to 5 seconds for an incoming connection
auto handle = server_socket.timedAccept(5000);
if (!handle)
{
std::cerr << "Timed out waiting for a client.\n";
return 1;
}
// The accepted handle owns the new connection until it is moved
NET::TCPSocket session = std::move(*handle);
std::cout << "Client connected from "
<< session.getForeignAddress() << ":"
<< session.getForeignPort() << "\n";
// sendAll() keeps sending until the complete buffer was handled
NET::IOResult sent = session.sendAll(hello_msg, hello_len);
{
std::cerr << "Client disconnected while sending.\n";
return 1;
}
// Gracefully signal that no more data will be sent
// The socket could still receive data after this call
std::cout << "Successfully sent " << sent.bytes << " bytes.\n";
}
// No explicit close is necessary
return 0;
}
catch (const NET::SocketException& e)
{
std::cerr << e.what() << std::endl;
return 1;
}
}
void bind(unsigned short localPort=0)
std::string getForeignAddress() const
unsigned short getForeignPort() const
void setReuseAddress(bool enable)
Enable or disable local address reuse.
void shutdown(ShutdownDirection type)
shutdown the connection in the specified direction
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
std::optional< TCPSocket > timedAccept(int timeout) const
wait for another socket to connect
void listen(int backlog=128)
listen for incoming connections
IOResult sendAll(const void *buffer, size_t len)
send data through a connected socket
@ STOP_SEND
disable all variants of send() on the socket, receive calls still work
IOStatus status