This is an example for a very simple TCP server application.
#include <simple_socket/TCPSocket.h>
#include <iostream>
static const char send_msg[] = "The quick brown fox jumps over the lazy dog";
static const size_t send_len = sizeof(send_msg) - 1;
int main()
{
try {
server_socket.
bind(
"127.0.0.1", 47777);
std::cout << "Waiting for a client..." << std::endl;
if (!handle)
{
std::cerr << "Timed out waiting for a client." << std::endl;
return 1;
}
int sent = session_socket.
sendAll(send_msg, send_len);
if (sent != static_cast<int>(send_len))
{
std::cerr << "Client disconnected while sending." << std::endl;
return 1;
}
std::cout << "Successfully sent " << sent << " bytes." << std::endl;
}
{
std::cerr << e.
what() << std::endl;
return 1;
}
return 0;
}
void bind(unsigned short localPort=0)
unsigned short getForeignPort() const
void setReuseAddress(bool enable)
Enable or disable local address reuse.
std::string getForeignAddress() const
void shutdown(ShutdownDirection type)
shutdown the connection in the specified direction
@ STOP_SEND
disable all variants of send() on the socket, receive calls still work
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.
void listen(int backlog=5)
Listen for incoming connections.
int sendAll(const void *buffer, size_t len)
Send the complete buffer.
SocketHandle< TCPSocket > Handle
Handle for a new socket returned by accept().
Handle timedAccept(int timeout) const
wait for another socket to connect