Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

Push Framework - A C++ toolkit for high performance server development

, 23 May 2012
Write asynchronous, multithreaded servers in a few lines of code. Monitor realtime activity with a deploy-only dashboard.
Prize winner in Competition "Best C++/MFC article of March 2011"
ChatApplication.zip
ChatAPI
ChatClient
res
.svn
entries
prop-base
ChatClient.ico.svn-base
props
text-base
ChatClient.ico.svn-base
ChatClient.rc2.svn-base
tmp
prop-base
props
text-base
ChatClient.ico
ChatPackets
ChatProtocol
ChatServer
ChatServer.vcproj.INTERNAL.Ahmed.Charfeddine.user
output
ChatServer.ini
TCPSocket
TCPSocket.zip
XMLProtocol
XMLProtocol.zip
ChatRobots.zip
ChatRobots
ChatRobots.ini
ProtoBufExample.zip
ProtoBufExampleClient
ProtoBufExampleProtocol
requests.pb.cc
responses.pb.cc
ProtoBufExampleServer
PushFramework_Essentials.zip
include
PushFramework_Sources.zip
private
QoS.zip
QoSExampleClient
QoSExampleProtocol
QoSExampleServer
/********************************************************************
	File :			ServerImpl.cpp
	Creation date :	2010/6/27
		
	License :			Copyright 2010 Ahmed Charfeddine, http://www.pushframework.com

				   Licensed under the Apache License, Version 2.0 (the "License");
				   you may not use this file except in compliance with the License.
				   You may obtain a copy of the License at
				
					   http://www.apache.org/licenses/LICENSE-2.0
				
				   Unless required by applicable law or agreed to in writing, software
				   distributed under the License is distributed on an "AS IS" BASIS,
				   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
				   See the License for the specific language governing permissions and
				   limitations under the License.
	
	
*********************************************************************/
#include "StdAfx.h"
#include "ServerImpl.h"

#include "Demultiplexor.h"
#include "Dispatcher.h"
#include "ServerStats.h"
#include "IOCPQueue.h"
#include "Acceptor.h"
#include "MonitorAcceptor.h"
#include "..\include\BroadcastManager.h"
#include "ChannelFactory.h"
#include "MonitorProtocol.h"
#include "..\include\ClientFactory.h"
#include "ClientFactoryImpl.h"
#include "BroadcastManagerImpl.h"
#include "..\include\server.h"

#include <mmsystem.h>


namespace PushFramework{

	void ServerImpl::setProtocol( Protocol* pProtocol )
	{
		this->pProtocol = pProtocol;
	}

	void ServerImpl::setClientFactory( ClientFactory* pClientFactory )
	{
		this->pClientFactory = pClientFactory;
		pClientFactory->pImpl->setServerImpl(this);
	}

	



	void ServerImpl::setWorkerCount( int workerCount )
	{
		this->workerCount = workerCount;
	}

	ClientFactory* ServerImpl::getClientFactory()
	{
		return pClientFactory;
	}

	BroadcastManager* ServerImpl::getBroadcastManager()
	{
		return pBroadcastManager;
	}

	Dispatcher* ServerImpl::getDispatcher()
	{
		return pDispatcher;
	}

	unsigned int ServerImpl::getSamplingRate()
	{
		return samplingRate;
	}

	ServerStats* ServerImpl::getStats()
	{
		return pStats;
	}

	ChannelFactory* ServerImpl::getChannelFactory()
	{
		return pChannelFactory;
	}

	IOCPQueue* ServerImpl::getIOCPQueue()
	{
		return pIOCPQueue;
	}

	std::string ServerImpl::getMonitorPassword()
	{
		return password;
	}

	void ServerImpl::eternal_loop()
	{
		//Periodic Timer
		m_hEventTimer = CreateEvent(NULL, TRUE, FALSE, NULL);
		ResetEvent(m_hEventTimer);
		//Abort event. (set by Stop function)
		m_hEventAbort = CreateEvent(NULL, TRUE, FALSE, NULL);
		ResetEvent(m_hEventAbort);
		//

		HANDLE			hWaits[2];
		hWaits[0]		= m_hEventTimer;
		hWaits[1]		= m_hEventAbort;


		UINT			sleepTimeMs=1000;//1 second.

		int nSecsGCCount=0;
		int nSecsPerfObservCount=0;
		//

		while(true)
		{
			MMRESULT result = timeSetEvent(sleepTimeMs, 1,
				(LPTIMECALLBACK) m_hEventTimer, 0, TIME_ONESHOT|TIME_CALLBACK_EVENT_SET);
			_ASSERT(result != NULL);

			// Sleep here until the timer interval ends or abort occurs
			if(WaitForMultipleObjects(2, hWaits, FALSE, INFINITE)==0)
			{

				nSecsGCCount++;
				nSecsPerfObservCount++;

				if(nSecsGCCount==uGCPeriod)
				{
					nSecsGCCount=0;
					pIOCPQueue->PostCustomEvent(IOGarbageCollection);
					//Beep( 750, 300 );
				}

				if(nSecsPerfObservCount==samplingRate && isProfilingEnabled)
				{
					nSecsPerfObservCount=0;
					pIOCPQueue->PostCustomEvent(IOPerformanceCollection);
				}
				ResetEvent(m_hEventTimer);
			}
			else
			{
				//m_hEventAbort is set : break from while.
				break;
			}
			//
		}

		CloseHandle(m_hEventAbort);
		CloseHandle(m_hEventTimer);
		//quit blocking.
	}

	unsigned __stdcall ServerImpl::threadProc( LPVOID WorkContext )
	{
		ServerImpl* pMe = reinterpret_cast<ServerImpl*>(WorkContext);
		pMe->eternal_loop();
		return 0;
	}

	void ServerImpl::start( bool startInSeparateThread )
	{
		if(pClientFactory == NULL)
			throw std::exception("Fatal : no ClientFactory instance was set");

		assignDefaultProtocol();

		if (!pIOCPQueue->Create())
			throw std::exception("Internal problem : unable to create iocp queue");

		if (!pDemux->start())
		{
			pIOCPQueue->Free();
			throw std::exception("Internal problem : unable to start demultiplexor");
		}

		if (!startListeners())
		{
			stopListeners();
			pDemux->stop();
			pIOCPQueue->Free();
		}


		if ( isMonitorEnabled && !pMonitorAcceptor->startListening())
		{
			stopListeners();
			pDemux->stop();
			pIOCPQueue->Free();
			throw std::exception("Internal problem : unable to start monitoring acceptor");
		}

		if (startInSeparateThread)
		{
			UINT  nThreadID;

			hThread = (HANDLE)_beginthreadex(NULL,// Security
				0,						// Stack size - use default
				threadProc,     		// Thread fn entry point
				(void*) this,			// Param for thread
				0,						// Init flag
				&nThreadID);			// Thread address
		}
		else
			eternal_loop();

	}

	void ServerImpl::stop()
	{
		SetEvent(m_hEventAbort);//stops eternal_loop

		if (isMonitorEnabled)
			pMonitorAcceptor->stopListening();


		stopListeners();


		pDemux->stop();

		pBroadcastManager->pImpl->disposeAllPackets();

		pIOCPQueue->Free();
	}

	void ServerImpl::registerService( unsigned int serviceId, Service* pService, const char* serviceName )
	{
		pDispatcher->registerService(serviceId, pService, serviceName);
	}

	ServerImpl::ServerImpl( Server* pFacade )
	{
		//Initialize WinSock :
		WSADATA wsaData;
		WSAStartup(MAKEWORD(2,2), &wsaData);

		this->pFacade = pFacade;

		pProtocol = NULL;
		pClientFactory = NULL;
		listeningPort = 2010;

		SYSTEM_INFO sysinfo;
		GetSystemInfo( &sysinfo );
		workerCount = sysinfo.dwNumberOfProcessors * 2;


		isMonitorEnabled = false;
		isProfilingEnabled = false;
		monitorPort = 2011;
		samplingRate = 10;
		password = "";

		pIOCPQueue = new IOCPQueue();
		pDemux = new Demultiplexor(this);
		pChannelFactory = new ChannelFactory(this);
		pDispatcher = new Dispatcher(this);

		pMonitorAcceptor = new MonitorAcceptor(this);
		pStats = new ServerStats(this);
		pBroadcastManager = new BroadcastManager();
		pBroadcastManager->pImpl->setServerImpl(this);

		uGCPeriod = 10;
	}

	ServerImpl::~ServerImpl( void )
	{
		delete pIOCPQueue;
		delete pDemux;
		delete pDispatcher;
		delete pChannelFactory;

		delete pMonitorAcceptor;
		delete pStats;
		delete pBroadcastManager;
	}

	Server* ServerImpl::getFacade()
	{
		return pFacade;
	}

	void ServerImpl::enableRemoteMonitor( short sPort, const char* password )
	{
		this->monitorPort = sPort;
		this->password = password;
		isMonitorEnabled = true;
		pMonitorAcceptor->setListeningPort(monitorPort);
	}

	void ServerImpl::enableProfiling( unsigned int samplingRate )
	{
		if (samplingRate >= 0)
		{
			this->samplingRate = samplingRate;
		}
		
		isProfilingEnabled = true;
	}

	void ServerImpl::disableProfiling()
	{
		isProfilingEnabled = false;
	}

	bool ServerImpl::getProfilingStatus()
	{
		return isProfilingEnabled;
	}

	void ServerImpl::setServeInfos( const char* serverInfos )
	{
		this->serverInfos = serverInfos;
	}

	std::string ServerImpl::getServerInfos()
	{
		return serverInfos;
	}

	


	void ServerImpl::setLoginExpiryDuration( unsigned int uLoginExpireDuration )
	{
		pChannelFactory->setLoginExpiryDuration(uLoginExpireDuration);
	}

	void ServerImpl::pause()
	{
		stopListeners();
	}

	void ServerImpl::resume()
	{
		startListeners();
	}

	void ServerImpl::getVersion( Version& ver )
	{
		ver.major = 1;
		ver.minor = 0;
		ver.monitorProtocolVer = 1;
	}

	int ServerImpl::getWorkerCount()
	{
		return workerCount;
	}

	BroadcastManagerImpl* ServerImpl::getBroadcastManagerImpl()
	{
		return pBroadcastManager->pImpl;
	}

	bool ServerImpl::createListener( int port, ListenerOptions* pOptions /*= NULL*/ )
	{
		listenersMapT::iterator it = listenersMap.find(port);
		if (it != listenersMap.end())
			return false;

		Acceptor* pAcceptor = new Acceptor(this);
		pAcceptor->setListeningPort(port);

		if (pOptions)
			pAcceptor->getOptions() = *pOptions;

		listenersMap[port] =  pAcceptor;
		return true;
	}


	

	bool ServerImpl::startListeners( )
	{
		for (listenersMapT::iterator it = listenersMap.begin();
			it!=listenersMap.end();
			it++)
		{
			Acceptor* pAcceptor = it->second;
			//
			//Start it :
			if (!pAcceptor->startListening())
			{
				return false;
				
			}
		}
		return true;
	}

	void ServerImpl::assignDefaultProtocol()
	{
		for (listenersMapT::iterator it = listenersMap.begin();
			it!=listenersMap.end();
			it++)
		{
			Acceptor* pAcceptor = it->second;
			//
			if(pAcceptor->getOptions().pProtocol == NULL)
			{
				if(pProtocol == NULL)
				{
					std::string strError = Utilities::stringBuilderA("FATAL : no protocol instance for acceptor on port : %d", it->first);
					throw std::exception(strError.c_str());
				}
				pAcceptor->getOptions().pProtocol = pProtocol;
			}
		}
	}

	void ServerImpl::stopListeners()
	{
		for (listenersMapT::iterator it = listenersMap.begin();
			it!=listenersMap.end();
			it++)
		{
			Acceptor* pAcceptor = it->second;
			pAcceptor->startListening();
		}
	}

	void ServerImpl::setMaxConnections( int nMaxConnections )
	{
		pChannelFactory->setMaxAllowedConnections(nMaxConnections);
	}

	void ServerImpl::EncodeOnAllProtocols( OutgoingPacket& outgoingPacket )
	{
		for (listenersMapT::iterator it = listenersMap.begin();
			it!=listenersMap.end();
			it++)
		{
			Protocol* pProtocol = it->second->getOptions().pProtocol;
			pProtocol->encodeOutgoingPacket(outgoingPacket);
		}
	}

}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Apache License, Version 2.0

Share

About the Author

Ahmed Charfeddine
Technical Lead
Tunisia Tunisia
Engineer in telecommunications, C++ developer and Amateur Chess Programmer.
Websites:
http://www.pushframework.com
http://www.batchdocument.com
http://www.virtualglobe3d.com
http://www.chesscomposer.com
 
I am open to any collaboration or freelance project.
Follow on   Twitter

| Advertise | Privacy | Mobile
Web02 | 2.8.140821.2 | Last Updated 23 May 2012
Article Copyright 2011 by Ahmed Charfeddine
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid