/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * COPYING NOTES
 *
 * server.cpp -- main server body
 * 
 * Copyright (C) 2002 Roberto A. Foglietta <robang@libero.it>
 * Copyright (C) 2002 GEA-Automotive <fogliettar@gea-automotive.com>
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 */

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 
 * REVISION NOTES:
 * released 21-10-2002 by Roberto A. Foglietta
 */
 
#include "../ServerSocket.h"
#include "../SocketException.h"
#include <iostream>
#include <cstring>
#include <string>
#include <cassert>


extern "C"
{
#include "replyfunc.h"
#include "mysignal.h"
}

int
main (int argc, char *argv[])
{
	int port;
	char *str;

	if (argc == 2)
		port = atoi (argv[1]);
	else
		port = _PORT;
	std::cout << "running on port " << port << " ...\n";


	signal (SIGINT, catch_int);

	while (true) {
		try {
			// Create the socket
			ServerSocket server (port);
			ServerSocket new_sock;
			server.accept (new_sock);

			while (true) {
				try {
					while (true) {
						std::string data;

						new_sock >> data;
						std::cout << "received:\n" << data << "\n";

						if (CTRL_C_FLAG) {
							std::cout << "sent:\n" << _STOP << "\n";
							new_sock << _STOP << "\n";
							return 0;
						}
						str = reply_func (data.c_str ());
						if (str) {
							new_sock << (std::string) str;
							std::cout << "sent:\n" << (std::string) str << "\n";
						} else {
							new_sock << _FAIL;
							std::cout << "sent:\n" << _FAIL << "\n";
						}
					}
				}
				catch (SocketException & e) {
					std::cout << "Exception was caught:" << e.description () << "\nrestarting.\n";
					break;
				}
			}
		}
		catch (SocketException & e) {
			std::cout << "Exception was caught:" << e.description () << "\nExiting.\n";
			return 1;
		}
	}

	return 0;
}