/***************************************************************************
*   Copyright (C) 2006 by Ian Reinhart Geiser   *
*   geiseri@kde.org   *
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU Library General Public License as       *
*   published by the Free Software Foundation; either version 2 of the    *
*   License, or (at your option) any later version.                       *
*                                                                         *
*   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 Library 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.             *
***************************************************************************/
#ifndef KRPCSERVER_H
#define KRPCSERVER_H

#include <QTcpServer>

#include <commandthread.h>


namespace KRPC
{
	/**
	Basic server listener.  Will listen for connections on a port and fork off a handler in a thread.

		@author Ian Reinhart Geiser <geiseri@kde.org>
	*/
	class Server : public QTcpServer
	{
		Q_OBJECT
	public:
		Server( QObject *parent = 0 );

		~Server();
	public slots:
		void start(  const QHostAddress &address = QHostAddress::Any, uint port = 8080);
		void stop();

	private slots:
		void finishThread();

	signals:
		void exitThreads();

	protected:
	/**
	 * Hanlde an new connection by starting a thread with the current socketDescriptor.
	 */
		void incomingConnection(int socketDescriptor);
	private:
		/**
		 * If there are more m_children than m_maxChildren then we will not create
		 * any new threads.  Instead we will spin in our event loop so we can queue
		 * new connections but allow current ones to exit.
		 */
		void throttleConnections();
		int m_children;
		int m_maxChildren;
		QList<CommandThread*> m_threadPool;
	};

}

#endif

