/*
 * A trivial server.  Clients connect and send their name, and the
 * server sends back a message Hello, name.  Uses traditional \r\n
 * line terminators.
 */
#include <iostream>
#include <cleansocks.h>
#include <cleanip.h>
#include <cleanbuf.h>
using namespace cleansocks;
int main(int argc, char **argv)
{
        // Takes a port number from the command line.
        if(argc != 2) {
                // Ooops!
                std::cerr << "Usage " << argv[0] << " port"
                          << std::endl;
                exit(1);
        }
        // Get a port number and build a listening socket.
        IPport port = atoi(argv[1]);
        TCPsocket listener;
        bind(listener, IPendpoint(IPaddress::any(),port));
        listen(listener);
        // Wait for and process connections.
        while(true) {
                // Get the socket
                IPendpoint rmt;
                TCPsocket s = accept(listener, rmt);
                std::cout << "Accepted connection from " << rmt << std::endl;
                
                // Buffering is nice for this.
                buffered_socket bsock(s);
                // Don't die when things crash.  Just try again.
                try {
                        // Get and answer.
                        char msg[1024];
                        int n = recvln(bsock, msg, sizeof msg);
                        // Transmission should end with \r\n.  Also, if
                        // the client just disconnects, we'll get zero.
                        // For either, go around.
                        if(n < 2) {
                                std::cout << "Bad transmission from "
                                          << rmt << std::endl;
                                close(bsock);
                                continue;
                        }
                        std::string name(msg, n-2);
                        std::cout << "I have " << name << " on the line."
                                  << std::endl;
                        // Answer.
                        send(bsock, "Hello, " + name + "!\r\n");
                } catch(socket_error &e) {
                        std::cout << e.what() << std::endl;
                }
                close(bsock);
        }
}