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 {
server_socket.
bind(
"127.0.0.1", 47777);
while(true)
{
std::cout << "Waiting for a client...\n";
if (!handle)
{
std::cerr << "Timed out waiting for a client.\n";
return 1;
}
std::cout << "Client connected from "
{
std::cerr << "Client disconnected while sending.\n";
return 1;
}
std::cout <<
"Successfully sent " << sent.
bytes <<
" bytes.\n";
}
return 0;
}
{
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.
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