Click here to Skip to main content
11,486,673 members (73,898 online)
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 Apache 140.4K 21.9K 291
Write asynchronous, multithreaded servers in a few lines of code. Monitor realtime activity with a deploy-only dashboard.
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.dll
PushFramework.lib
PushFramework_Sources.zip
private
QoS.zip
QoSExampleClient
QoSExampleProtocol
QoSExampleServer
/********************************************************************
	File :			ChannelFactory.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 "ChannelFactory.h"

#include "ServerImpl.h"
#include "IOCPQueue.h"
#include "Dispatcher.h"

#include "Listener.h"

#include "ScopedLock.h"


namespace PushFramework{


ChannelFactory::ChannelFactory(ServerImpl* pServerImpl)
{
	this->pServerImpl = pServerImpl;
	::InitializeCriticalSection(&csChannelMap);
	
	uLoginExpireDuration = 40;
	nMaxConnections = 100;

	isPermitOnly = false;
}

ChannelFactory::~ChannelFactory(void)
{
	for (channelMapT::iterator it=channelMap.begin();
		it!=channelMap.end();
		it++
		)
	{
		CChannel* pChannel = it->second;
		delete pChannel;
	}

	::DeleteCriticalSection(&csChannelMap);
}

void ChannelFactory::addObject( CChannel* pChannel )
{
	ScopedLock lock(csChannelMap);
	
	channelMap[pChannel->getKey()] = pChannel;
}

CChannel* ChannelFactory::getObject( CChannel::Key key )
{
	ScopedLock lock(csChannelMap);
	
	channelMapT::iterator it = channelMap.find(key);
	if (it == channelMap.end())
		return NULL;

	CChannel* pChannel = it->second;
	::InterlockedIncrement ( (long*)&pChannel->getRefCount() );
	return pChannel;
}

void ChannelFactory::disposeObject( CChannel::Key key )
{
	ScopedLock lock(csChannelMap);

	channelMapT::iterator it = channelMap.find(key);
	if (it == channelMap.end())
		return;

	CChannel* pChannel = it->second;
	::InterlockedDecrement ( (long*)&pChannel->getRefCount() );

	if (pChannel->getRefCount()== 0 && pChannel->getStatus()==CChannel::Released)
	{
		disposeChannel(pChannel);
		channelMap.erase(it);
	}
}

void ChannelFactory::removeObject( CChannel::Key key )
{
	ScopedLock lock(csChannelMap);

	channelMapT::iterator it = channelMap.find(key);
	if (it == channelMap.end())
		return;

	CChannel* pChannel = it->second;
	
	disposeChannel(pChannel);

	channelMap.erase(it);
}

void ChannelFactory::closeNonLogged()
{
	unsigned int uLoginExpireDurationMn = 40;

	wcout << L"closeNonLogged"<<std::endl;
	ScopedLock lock(csChannelMap);

	for (channelMapT::iterator it=channelMap.begin();
		it!=channelMap.end();
		)
	{
		CChannel* pChannel = it->second;
		if (pChannel->getStatus()==CChannel::Connected)
		{
			if (pChannel->getLifeDuration() > COleDateTimeSpan(0,0,0,pChannel->isObserverChannel() ? uLoginExpireDurationMn : uLoginExpireDuration))
			{
				wcout << L"Disconnecting an unlogged channel"<<std::endl;
				pChannel->Close(false);
				if (pChannel->getRefCount() == 0 && pChannel->getPostedIOs()==0)
				{
					disposeChannel(pChannel);
					it = channelMap.erase(it);
					continue;
				}				
			}						
		}
		it++;
	}	
}

void ChannelFactory::BroadcastToMonitors( OutgoingPacket* pPacket )
{
	ScopedLock lock(csChannelMap);

	for (channelMapT::iterator it=channelMap.begin();
		it!=channelMap.end();
		it++
		)
	{
		CChannel* pChannel = it->second;
		if (pChannel->isObserverChannel() &&
			pChannel->getStatus()==CChannel::Attached)
		{
			pChannel->PushPacket(pPacket);					
		}
	}
}

void ChannelFactory::ProcessPendingObserversPackets()
{
	ScopedLock lock(csChannelMap);

	for (channelMapT::iterator it=channelMap.begin();
		it!=channelMap.end();
		it++
		)
	{
		CChannel* pChannel = it->second;
		if (pChannel->isObserverChannel() &&
			pChannel->getStatus()==CChannel::Attached)
		{
			pServerImpl->getDispatcher()->ProcessClientPendingPackets(pChannel);
		}
	}
}

void ChannelFactory::ProcessPendingClientPackets( std::string broadcastChannel )
{
	ScopedLock lock(csChannelMap);

	for (channelMapT::iterator it=channelMap.begin();
		it!=channelMap.end();
		it++
		)
	{
		CChannel* pChannel = it->second;
		if (!pChannel->isObserverChannel() &&
			pChannel->getStatus()==CChannel::Attached)
		{
			pServerImpl->getDispatcher()->ProcessClientPendingPackets(pChannel);
		}
	}
}

void ChannelFactory::disposeChannel( CChannel* pChannel )
{
	pChannel->unintialize();
	//
	delete pChannel;
		
}

void ChannelFactory::setLoginExpiryDuration( unsigned int uLoginExpireDuration )
{
	this->uLoginExpireDuration = uLoginExpireDuration;
}

void ChannelFactory::setMaxAllowedConnections( unsigned int nMaxConnections )
{
	this->nMaxConnections = nMaxConnections;
}

bool ChannelFactory::SetupPhysicalConnection( SOCKET hSocket, ListenerOptions* pListenerOptions, SOCKADDR_IN address, bool isObserver )
{
	CChannel* pChannel = new CChannel(pServerImpl, pListenerOptions);
	
	pChannel->initialize(hSocket, address, isObserver);

	//Now Associate with IOCP main Handle
	if (!pServerImpl->getIOCPQueue()->AddSocketContext(hSocket, (DWORD) pChannel))
	{
		disposeChannel(pChannel);
		//leave socket close to acceptor
		return false;
	}

	addObject(pChannel);

	//Unlocking iocp event:
	if(!pServerImpl->getIOCPQueue()->InitializeSocketContext( (DWORD) pChannel))
	{
		removeObject(pChannel->getKey());
		//leave socket close to acceptor
		return false;
	}

	return true;
}

bool ChannelFactory::SetupClientConnection( SOCKET hSocket, SOCKADDR_IN address, Listener* pListener )
{
	//Check if max connections is not exceeded.
	if (channelMap.size() >= nMaxConnections)
	{
		return false;
	}

	//Check if address is not blocked :
	if (!isNotBlockedAddress(address.sin_addr))
	{
		return false;
	}

	//
	return SetupPhysicalConnection(hSocket, &pListener->getOptions(), address, false);
}

bool ChannelFactory::SetupDashboardConnection( SOCKET hSocket, SOCKADDR_IN address, Listener* pListener )
{
	return SetupPhysicalConnection(hSocket, &pListener->getOptions(), address, true);
}

bool ChannelFactory::isNotBlockedAddress( IN_ADDR SockAddr )
{
	long ip = 0;

	ip = SockAddr.S_un.S_un_b.s_b1 * 16777216 + SockAddr.S_un.S_un_b.s_b2 * 65536 + 	SockAddr.S_un.S_un_b.s_b3 * 256 + 	SockAddr.S_un.S_un_b.s_b4;

	bool bAllow = false;

	ipRangeListT& list = isPermitOnly ? permittedIPs : blockedIPs;
	bool bIsInList = false;

	for (int i=0;i<list.size();i++)
	{
		IPRange& ipRange = list.at(i);

		long start = 0;
		long stop = 0;

		start = ipRange.startIP.S_un.S_un_b.s_b1 * 16777216 + ipRange.startIP.S_un.S_un_b.s_b2 * 65536 + 	ipRange.startIP.S_un.S_un_b.s_b3 * 256 + 	ipRange.startIP.S_un.S_un_b.s_b4;
		stop = ipRange.endIP.S_un.S_un_b.s_b1 * 16777216 + ipRange.endIP.S_un.S_un_b.s_b2 * 65536 + 	ipRange.endIP.S_un.S_un_b.s_b3 * 256 + 	ipRange.endIP.S_un.S_un_b.s_b4;


		if (ip <= stop && ip >= start)
		{
			bIsInList = true;
			break;
		}
	}
	return isPermitOnly ? bIsInList : !bIsInList;
}

void ChannelFactory::addIPRangeAccess( const char* ipStart, const char* ipStop, bool bPermit )
{
	isPermitOnly = bPermit;

	IPRange ipRange;

	/*
	ipRange.startIP = inet_addr(ipStart);
		ipRange.endIP = inet_addr(ipStop);*/
	

	ipRangeListT& list = bPermit ? permittedIPs : blockedIPs;

	list.push_back(ipRange);
}

}

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
Services:
http://www.pushframework.com/?page_id=890
Follow on   Twitter

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150520.1 | Last Updated 23 May 2012
Article Copyright 2011 by Ahmed Charfeddine
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid