Click here to Skip to main content
15,885,278 members
Articles / Web Development / HTML

Server Wizard

Rate me:
Please Sign up or sign in to vote.
4.83/5 (6 votes)
1 Feb 2013CPOL7 min read 31.1K   1.9K   33  
A Visual C++ Project Wizard for the fast creation of high performance TCP servers in C++
/********************************************************************
	File :			DemuxImpl_Win.cpp
	Creation date :	2012/01/29

	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 "DemuxImpl_Win.h"

#include "Demultiplexor.h"
#include "ServerImpl.h"

#ifdef Plateform_Windows
#include "IOQueue_Win.h"
#elif Plateform_Linux
#include "IOQueue_Linux.h"
#endif

#include "Dispatcher.h"
#include "PhysicalConnection.h"
#include "../include/Server.h"
#include "../include/ServerOptions.h"

namespace PushFramework
{

DemuxImpl::DemuxImpl(Demultiplexor* pFacade)
{
    this->pFacade = pFacade;
	g_hShutdownEvent	= NULL;
}

DemuxImpl::~DemuxImpl()
{
}

bool DemuxImpl::start()
{
    g_hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

    DWORD  nThreadID;

    for ( unsigned int i = 0; i < options.nWorkersCount; i++ )
    {

        HANDLE hThread = CreateThread(NULL,				// Security
                               0,						// Stack size - use default
                               KerIOCPWorkerProc,     	// Thread fn entry point
                               (void*) this,			// Param for thread
                               0,						// Init flag
                               &nThreadID);				// Thread address
		if (hThread)
		{
			workersThreadsVect.push_back(hThread);
		}
		else
		{
			stop();
			return false;
		}
    }
    return true;
}

void DemuxImpl::stop()
{
	if(workersThreadsVect.empty())
		return;
	
	SetEvent(g_hShutdownEvent);

	HANDLE *pThreads = new HANDLE[workersThreadsVect.size()];
	for (size_t i = 0; i < workersThreadsVect.size(); i++)
	{
		pThreads[i] = workersThreadsVect.at(i);
		// Ensure all workers will awake from GetQueuedCompletionStatus
		ioQueue.postTerminationSignal();
	}

    WaitForMultipleObjects(workersThreadsVect.size(), pThreads, TRUE, INFINITE);
	
	CloseHandle(g_hShutdownEvent);
}
DWORD WINAPI DemuxImpl::KerIOCPWorkerProc( LPVOID WorkContext )
{
    DemuxImpl* pThis = reinterpret_cast<DemuxImpl*>(WorkContext);

    pThis->proc();

    return 0;
}

void DemuxImpl::proc()
{
    void* perThreadCtx = pServerImpl->getFacade()->workerThreadBegin();


    DWORD dwIoSize;
    PhysicalConnection *pPerSocketContext = NULL;
    LPOVERLAPPED lpOverlapped;//Passed to GetCompletionStatus to point to the completed operation's buffer
    OVERLAPPEDPLUS  *pPerIOContext;//OverlapPlus associated to the lpOverlapped returned by GetCompletionStatus(..


    while (WAIT_OBJECT_0 != WaitForSingleObject(g_hShutdownEvent, 0))
    {
        BOOL bSuccess = ioQueue.getQueuedEvent(&dwIoSize,(ULONG_PTR*) &pPerSocketContext,&lpOverlapped);

        if(!bSuccess)
        {
			if (pPerSocketContext)
			{
				// when the socket is closed, all pending IOs on the completion port are
				// cancelled. We should decrement the physical connection reference counter
				// to allow for the safe disposal of both the logical connection and its physical
				// connection structure.
				dispatcher.handleFailedIO(pPerSocketContext);
			}
            continue;
        }
        if (pPerSocketContext==NULL)
        {
            // Signal to stop.
            break;
        }

        pPerIOContext = CONTAINING_RECORD(lpOverlapped, OVERLAPPEDPLUS, m_ol);
        switch (pPerIOContext->m_ioType)
        {
        case IORead:
            dispatcher.handleRead(pPerSocketContext,dwIoSize);
            break;
        case IOWrite:
            dispatcher.handleWrite(pPerSocketContext,dwIoSize);
            break;
        case IOInitialize:
            dispatcher.handleInitialize(pPerSocketContext);
            delete pPerIOContext;
            break;
        default:
            break;
        }//end of switch

    }//end of while
    pServerImpl->getFacade()->workerThreadEnd(perThreadCtx);
}

}

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 Code Project Open License (CPOL)


Written By
Technical Lead
Tunisia Tunisia
Services:
http://www.pushframework.com/?page_id=890

Comments and Discussions