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

RCF - Interprocess Communication for C++

, 25 Oct 2011
A server/client IPC framework, using the C++ preprocessor as an IDL compiler.
rcf-04.zip
RCF-0.4
demo
vs2003
RCF
Client
Server
doc
html
class_r_c_f_1_1_exception.png
class_r_c_f_1_1_filter.png
class_r_c_f_1_1_filter_factory.png
class_r_c_f_1_1_filter_service.png
class_r_c_f_1_1_identity_filter.png
class_r_c_f_1_1_identity_filter_factory.png
class_r_c_f_1_1_i___client_transport.png
class_r_c_f_1_1_i___endpoint.png
class_r_c_f_1_1_i___service.png
class_r_c_f_1_1_i___session_manager.png
class_r_c_f_1_1_multicast_client_transport.png
class_r_c_f_1_1_object_factory_service.png
class_r_c_f_1_1_open_ssl_encryption_filter.png
class_r_c_f_1_1_open_ssl_encryption_filter_factory.png
class_r_c_f_1_1_publishing_service.png
class_r_c_f_1_1_rcf_server.png
class_r_c_f_1_1_remote_exception.png
class_r_c_f_1_1_subscription_service.png
class_r_c_f_1_1_tcp_endpoint.png
class_r_c_f_1_1_udp_endpoint.png
class_r_c_f_1_1_zlib_stateful_compression_filter_factory.png
class_r_c_f_1_1_zlib_stateless_compression_filter_factory.png
doxygen.png
ftv2blank.png
ftv2doc.png
ftv2folderclosed.png
ftv2folderopen.png
ftv2lastnode.png
ftv2link.png
ftv2mlastnode.png
ftv2mnode.png
ftv2node.png
ftv2plastnode.png
ftv2pnode.png
ftv2vertline.png
tab_b.gif
tab_l.gif
tab_r.gif
latex
annotated.tex
class_r_c_f_1_1_client_stub.tex
class_r_c_f_1_1_exception.eps
class_r_c_f_1_1_exception.tex
class_r_c_f_1_1_filter.eps
class_r_c_f_1_1_filter.tex
class_r_c_f_1_1_filter_description.tex
class_r_c_f_1_1_filter_factory.eps
class_r_c_f_1_1_filter_factory.tex
class_r_c_f_1_1_filter_service.eps
class_r_c_f_1_1_filter_service.tex
class_r_c_f_1_1_identity_filter.eps
class_r_c_f_1_1_identity_filter.tex
class_r_c_f_1_1_identity_filter_factory.eps
class_r_c_f_1_1_identity_filter_factory.tex
class_r_c_f_1_1_i___client_transport.eps
class_r_c_f_1_1_i___client_transport.tex
class_r_c_f_1_1_i___endpoint.eps
class_r_c_f_1_1_i___endpoint.tex
class_r_c_f_1_1_i___proactor.tex
class_r_c_f_1_1_i___rcf_client.tex
class_r_c_f_1_1_i___server_transport.tex
class_r_c_f_1_1_i___server_transport_ex.tex
class_r_c_f_1_1_i___service.eps
class_r_c_f_1_1_i___service.tex
class_r_c_f_1_1_i___session.tex
class_r_c_f_1_1_i___session_manager.eps
class_r_c_f_1_1_i___session_manager.tex
class_r_c_f_1_1_multicast_client_transport.eps
class_r_c_f_1_1_multicast_client_transport.tex
class_r_c_f_1_1_object_factory_service.eps
class_r_c_f_1_1_object_factory_service.tex
class_r_c_f_1_1_open_ssl_encryption_filter.eps
class_r_c_f_1_1_open_ssl_encryption_filter.tex
class_r_c_f_1_1_open_ssl_encryption_filter_factory.eps
class_r_c_f_1_1_open_ssl_encryption_filter_factory.tex
class_r_c_f_1_1_publishing_service.eps
class_r_c_f_1_1_publishing_service.tex
class_r_c_f_1_1_rcf_server.eps
class_r_c_f_1_1_rcf_server.tex
class_r_c_f_1_1_remote_exception.eps
class_r_c_f_1_1_remote_exception.tex
class_r_c_f_1_1_subscription_service.eps
class_r_c_f_1_1_subscription_service.tex
class_r_c_f_1_1_tcp_endpoint.eps
class_r_c_f_1_1_tcp_endpoint.tex
class_r_c_f_1_1_udp_endpoint.eps
class_r_c_f_1_1_udp_endpoint.tex
class_r_c_f_1_1_zlib_stateful_compression_filter.tex
class_r_c_f_1_1_zlib_stateful_compression_filter_factory.eps
class_r_c_f_1_1_zlib_stateful_compression_filter_factory.tex
class_r_c_f_1_1_zlib_stateless_compression_filter.tex
class_r_c_f_1_1_zlib_stateless_compression_filter_factory.eps
class_r_c_f_1_1_zlib_stateless_compression_filter_factory.tex
dirs.tex
dir_G_3A_2FDevelopment_2Fbuild_2Fscripts_2Fwin_2FBuildRcf2_5FOutput_2FRCF_2D0_2E4_2Finclude_2F.tex
dir_G_3A_2FDevelopment_2Fbuild_2Fscripts_2Fwin_2FBuildRcf2_5FOutput_2FRCF_2D0_2E4_2Finclude_2FRCF_2F.tex
dir_G_3A_2FDevelopment_2Fbuild_2Fscripts_2Fwin_2FBuildRcf2_5FOutput_2FRCF_2D0_2E4_2Finclude_2FRCF_2FProtocol_2F.tex
doxygen.sty
Helvetica.ttf
hierarchy.tex
Makefile
refman.tex
struct_r_c_f_1_1_filter_id_comparison.tex
include
RCF
Marshal.inl
Protocol
RcfServer.inl
ServerStub.inl
test
util
Platform
Machine
SPARC
x86
OS
Unix
Windows
Threads
SF
src
RCF
Protocol
SF
test
borland
Jamfile
Jamrules
Jamfile
Jamrules
vs2003
RCF
RCF
RCFTest
client.pem
server.pem
rcf-09c.zip
RCF-0.9c
demo
vs2003
RCF
Client
Server
include
RCF
Marshal.inl
Protocol
RcfServer.inl
ServerStub.inl
test
util
Platform
Machine
SPARC
x86
OS
Unix
Windows
Threads
SF
src
RCF
Protocol
util
SF
test
bcc
Jamfile
Jamrules
data
caCertA.pem
caCertB.pem
certA.pem
certB.pem
ssCert1.pem
ssCert2.pem
Jamfile
Jamrules
vc6
Jamfile
Jamrules
//*****************************************************************************
// RCF - Remote Call Framework
// Copyright (c) 2005. All rights reserved.
// Developed by Jarl Lindrud.
// Contact: jlindrud@hotmail.com .
//*****************************************************************************

#include <RCF/TcpAsioServerTransport.hpp>

#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>

#include <RCF/AsyncFilter.hpp>
#include <RCF/RcfServer.hpp>
#include <RCF/TcpAsioSynchronizedSocket.hpp>
#include <RCF/TcpAsioClientTransport.hpp>
#include <RCF/TcpEndpoint.hpp>

namespace RCF {

    TcpAsioServerTransport::SessionState::SessionState(TcpAsioServerTransport &transport, DemuxerPtr demuxerPtr, ReadWriteMutexPtr readWriteMutexPtr) : 
        mSynchronizedSocketPtr( new TcpAsioSynchronizedSocket(demuxerPtr, readWriteMutexPtr) ),
        mState(Ready),
        mReadBufferRemaining(),
        mWriteBufferRemaining(),
        mReflecting(),
        mTransport(transport)
    {
    }

    TcpAsioServerTransport::SessionState::~SessionState()
    {
    }

    TcpAsioServerTransport::TcpAsioProactor::TcpAsioProactor(TcpAsioServerTransport &tcpAsioServerTransport) :
        mTcpAsioServerTransport(tcpAsioServerTransport)
    {}

    void TcpAsioServerTransport::TcpAsioProactor::postRead()
    {
        SessionStatePtr sessionStatePtr( mSessionStateWeakPtr.lock() );
        RCF_ASSERT(sessionStatePtr.get());

        sessionStatePtr->mState = SessionState::ReadingDataCount;
        sessionStatePtr->mReadBuffer.resize(4);
        sessionStatePtr->mReadBufferRemaining = 4;
        sessionStatePtr->invokeAsyncRead();
    }

    void TcpAsioServerTransport::TcpAsioProactor::postWrite()
    {
        SessionStatePtr sessionStatePtr( mSessionStateWeakPtr.lock() );
        RCF_ASSERT(sessionStatePtr.get());
        RCF_ASSERT(sessionStatePtr->mWriteBuffer.size() > 4);
        BOOST_STATIC_ASSERT(sizeof(unsigned int) == 4);

        // prepend message length
        unsigned int *pLen = reinterpret_cast<unsigned int *>(&sessionStatePtr->mWriteBuffer[0]);
        *pLen = static_cast<unsigned int>(sessionStatePtr->mWriteBuffer.size() - 4);
        machineToNetworkOrder(pLen, 4, 1);

        sessionStatePtr->mState = SessionState::WritingData;
        sessionStatePtr->mWriteBufferRemaining = sessionStatePtr->mWriteBuffer.size();
        sessionStatePtr->invokeAsyncWrite();
    }

    void TcpAsioServerTransport::TcpAsioProactor::postClose()
    {
        SessionStatePtr sessionStatePtr( mSessionStateWeakPtr.lock() );
        RCF_ASSERT(sessionStatePtr.get());
        sessionStatePtr->close();
    }

    std::vector<char> &TcpAsioServerTransport::TcpAsioProactor::getWriteBuffer()
    {
        SessionStatePtr sessionStatePtr( mSessionStateWeakPtr.lock() );
        RCF_ASSERT(sessionStatePtr.get());
        return sessionStatePtr->mWriteBuffer;
    }

    std::size_t TcpAsioServerTransport::TcpAsioProactor::getWriteOffset()
    {
        return 4;
    }

    std::vector<char> &TcpAsioServerTransport::TcpAsioProactor::getReadBuffer()
    {
        SessionStatePtr sessionStatePtr( mSessionStateWeakPtr.lock() );
        RCF_ASSERT(sessionStatePtr.get());
        return sessionStatePtr->mReadBuffer;
    }

    std::size_t TcpAsioServerTransport::TcpAsioProactor::getReadOffset()
    {
        return 0;
    }

    I_ServerTransport &TcpAsioServerTransport::TcpAsioProactor::getServerTransport()
    {
        return mTcpAsioServerTransport;
    }

    const I_RemoteAddress &TcpAsioServerTransport::TcpAsioProactor::getRemoteAddress()
    {
        SessionStatePtr sessionStatePtr( mSessionStateWeakPtr.lock() );
        RCF_ASSERT(sessionStatePtr.get());
        return sessionStatePtr->mIpAddress;
    }

    void TcpAsioServerTransport::TcpAsioProactor::setTransportFilters(const std::vector<FilterPtr> &filters)
    {
        SessionStatePtr sessionStatePtr( mSessionStateWeakPtr.lock() );
        RCF_ASSERT(sessionStatePtr.get());
        sessionStatePtr->setTransportFilters(filters);
    }

    TcpAsioServerTransport::SessionStatePtr TcpAsioServerTransport::createSessionState()
    {
        SessionStatePtr sessionStatePtr( new SessionState(*this, mDemuxerPtr, mReadWriteMutexPtr) );
        mSessionStates.insert(sessionStatePtr);

        SessionPtr sessionPtr( getSessionManager().createSession() );
        TcpAsioProactorPtr tcpAsioProactorPtr( new TcpAsioProactor(*this) );
        sessionPtr->setProactorPtr( ProactorPtr(tcpAsioProactorPtr) );
        tcpAsioProactorPtr->mSessionStateWeakPtr = sessionStatePtr;
        sessionStatePtr->setSessionPtr(sessionPtr);
        return sessionStatePtr;
    }

    void TcpAsioServerTransport::SessionState::filteredRead(char *buffer, std::size_t bufferLen)
    {
        mSynchronizedSocketPtr->read(
            buffer, 
            bufferLen, 
            boost::bind(
                &SessionState::filteredReadWriteCompletion,
                shared_from_this(),
                asio::placeholders::error,
                asio::placeholders::bytes_transferred));
    }

    void TcpAsioServerTransport::SessionState::filteredWrite(const char *buffer, std::size_t bufferLen)
    {
        mSynchronizedSocketPtr->write(
            buffer, 
            bufferLen, 
            boost::bind(
                &SessionState::filteredReadWriteCompletion,
                shared_from_this(),
                asio::placeholders::error,
                asio::placeholders::bytes_transferred));
    }

    void TcpAsioServerTransport::SessionState::filteredReadWriteCompletion(const asio::error &error, size_t bytesTransferred)
    {
        mTransportFilters.empty() ?
            onReadWrite(error, bytesTransferred) :
            error ? 
                mTransportFilters.back()->onReadWriteCompleted(0, -1) :
                mTransportFilters.back()->onReadWriteCompleted(bytesTransferred, 0);
    }

    void TcpAsioServerTransport::SessionState::unfilteredReadWriteCompletion(std::size_t bytesTransferred, int error)
    {
        onReadWrite(asio::error(error), bytesTransferred);
    }

    void TcpAsioServerTransport::SessionState::setTransportFilters(const std::vector<FilterPtr> &filters)
    {
        mTransportFilters.assign(filters.begin(), filters.end());

        // TODO: shared_from_this() or this?
        Filter::ReadFunction readFunction( boost::bind(&SessionState::filteredRead, shared_from_this(), _1, _2) );
        Filter::WriteFunction writeFunction( boost::bind(&SessionState::filteredWrite, shared_from_this(), _1, _2) );
        Filter::ReadWriteCompletionCallback readWriteCompletionCallback( boost::bind(&SessionState::unfilteredReadWriteCompletion, shared_from_this(), _1, _2) );

        RCF::connectFilters(
            mTransportFilters,
            readFunction, 
            writeFunction, 
            readWriteCompletionCallback);
    }

    void TcpAsioServerTransport::SessionState::invokeAsyncRead()
    {
        std::size_t offset = mReadBuffer.size() - mReadBufferRemaining;
        char *buffer = &mReadBuffer[offset];
        std::size_t bufferLen = mReadBufferRemaining;

        mTransportFilters.empty() ?
            filteredRead(buffer, bufferLen) :
            mTransportFilters.front()->read(buffer, bufferLen);
    }

    void TcpAsioServerTransport::SessionState::invokeAsyncWrite()
    {
        std::size_t offset = mWriteBuffer.size() - mWriteBufferRemaining;
        char *buffer = &mWriteBuffer[offset];
        std::size_t bufferLen = mWriteBufferRemaining;

        mTransportFilters.empty() ?
            filteredWrite(buffer, bufferLen) :
            mTransportFilters.front()->write(buffer, bufferLen);
    }

    void TcpAsioServerTransport::SessionState::invokeAsyncAccept()
    {
        mState = SessionState::Accepting;

        mSynchronizedSocketPtr->accept(
            *mTransport.mAcceptorPtr, 
            boost::bind(
                &SessionState::onAccept,
                shared_from_this(),
                asio::placeholders::error));
    }

    void TcpAsioServerTransport::SessionState::onAccept(const asio::error& error)
    {
        if (!error)
        {
            // save the remote address in the SessionState object
            asio::ip::tcp::endpoint endpoint;
            mSynchronizedSocketPtr->getRemoteEndpoint(endpoint);
            sockaddr_in addr;
            memset(&addr, 0, sizeof(addr));
            addr.sin_family = AF_INET;
            addr.sin_port = endpoint.port();
            addr.sin_addr.s_addr = htonl(endpoint.address().to_v4().to_ulong());
            mIpAddress = IpAddress(addr);
            mState = SessionState::WritingData;

            // create a new SessionState, and do an accept on that
            mTransport.createSessionState()->invokeAsyncAccept();

            if (mTransport.isClientAddrAllowed(addr))
            {
                // start things rolling by faking a completed write operation
                onReadWrite(asio::error(0), 0);
            }
            else
            {
                mTransport.mSessionStates.erase(shared_from_this());
            }
        }
        else if (error == asio::error::connection_aborted)
        {
            invokeAsyncAccept();
        }
        else
        {
            mTransport.mSessionStates.erase(shared_from_this());
            mTransport.createSessionState()->invokeAsyncAccept();
        }
    }

    void TcpAsioServerTransport::SessionState::onReadWrite(const asio::error& error, size_t bytesTransferred)
    {
        if (mReflecting)
        {
            onReflectedReadWrite(error, bytesTransferred);
        }
        else if (!error)
        {
            switch(mState)
            {
            case SessionState::ReadingDataCount:
            case SessionState::ReadingData:
                RCF_ASSERT(bytesTransferred <= mReadBufferRemaining);
                mReadBufferRemaining -= bytesTransferred;
                if (mReadBufferRemaining > 0)
                {
                    invokeAsyncRead();
                }
                else
                {
                    RCF_ASSERT(mReadBufferRemaining == 0);
                    if (mState == SessionState::ReadingDataCount)
                    {
                        RCF_ASSERT(mReadBuffer.size() == 4);
                        unsigned int packetLength = * (unsigned int *) (&mReadBuffer[0]);
                        networkToMachineOrder(&packetLength, 4, 1);
                        if (packetLength <= mTransport.getMaxMessageLength())
                        {
                            mReadBuffer.resize(packetLength);
                            mReadBufferRemaining = packetLength;
                            mState = SessionState::ReadingData;
                            invokeAsyncRead();
                        }

                    }
                    else if (mState == SessionState::ReadingData)
                    {
                        mState = SessionState::Ready;
                        mTransport.getSessionManager().onReadCompleted(getSessionPtr());

                        // TODO: this stuff needs to go in TcpAsioServerTransport somewhere
                        // TODO: is this a good idea? maybe interrupt() instead?
                        mTransport.getServer().cycleSessions(0, mTransport.mStopFlag);

                        if (mTransport.mInterrupt)
                        {
                            mTransport.mInterrupt = false;
                            mTransport.mDemuxerPtr->interrupt();
                        }
                    }
                }
                break;


            case SessionState::WritingData:

                RCF_ASSERT(bytesTransferred <= mWriteBufferRemaining);
                mWriteBufferRemaining -= bytesTransferred;
                if (mWriteBufferRemaining > 0)
                {
                    invokeAsyncWrite();
                }
                else
                {
                    mState = SessionState::Ready;
                    mTransport.getSessionManager().onWriteCompleted(getSessionPtr());
                }
                break;

            default:
                RCF_ASSERT(0);
            }
        }
        else
        {
            // error, mark the socket as closed and release our reference to it
            mSynchronizedSocketPtr->setCloseFlag();
            mTransport.mSessionStates.erase(shared_from_this());
        }
    }

    void TcpAsioServerTransport::SessionState::onReflectedReadWrite(const asio::error& error, size_t bytesTransferred)
    {
        RCF_ASSERT(mReflecting);
        if (error)
        {
            mReflectorSocketPtr->close();
            mReflectorSocketPtr.reset();
            mSynchronizedSocketPtr->setCloseFlag();
            mTransport.mSessionStates.erase(shared_from_this());
        }
        else
        {
            char *buffer = NULL;
            std::size_t bufferLen = 0;
            switch (mState)
            {
            case SessionState::ReadingDataCount:
            case SessionState::ReadingData:
                mState = SessionState::WritingData;
                RCF_ASSERT(mReadBufferRemaining >= bytesTransferred);
                mReadBufferRemaining -= bytesTransferred;
                buffer = &mReadBuffer[0];
                bufferLen = mReadBuffer.size() - mReadBufferRemaining;
                mReflectorSocketPtr->write(
                    buffer, 
                    bufferLen, 
                    boost::bind(
                        &SessionState::onReflectedReadWrite, 
                        shared_from_this(), 
                        asio::placeholders::error, 
                        asio::placeholders::bytes_transferred));
                break;

            case SessionState::WritingData:
                mState = SessionState::ReadingData;
                mReadBuffer.resize(1024); //TODO: configurable block size
                mReadBufferRemaining = mReadBuffer.size();
                buffer = &mReadBuffer[0];
                bufferLen = mReadBufferRemaining;
                mSynchronizedSocketPtr->read(
                    buffer, 
                    bufferLen, 
                    boost::bind(
                        &SessionState::onReflectedReadWrite,
                        shared_from_this(),
                        asio::placeholders::error,
                        asio::placeholders::bytes_transferred));
                break;

            default:
                RCF_ASSERT(0);
            }
        }
    }

    // I_ServerTransportEx implementation

    ClientTransportAutoPtr TcpAsioServerTransport::createClientTransport(const I_Endpoint &endpoint)
    {
        const TcpEndpoint &tcpEndpoint = dynamic_cast<const TcpEndpoint &>(endpoint);
        ClientTransportAutoPtr clientTransportAutoPtr(
            new TcpAsioClientTransport(tcpEndpoint.getIp(), tcpEndpoint.getPort(), mDemuxerPtr));
        return clientTransportAutoPtr;
    }

    boost::shared_ptr<I_Session> TcpAsioServerTransport::createServerSession(ClientTransportAutoPtr clientTransportAutoPtr)
    {
        TcpAsioClientTransport *pTcpAsioClientTransport = dynamic_cast<TcpAsioClientTransport *>(clientTransportAutoPtr.get());
        if (pTcpAsioClientTransport == NULL ||
            pTcpAsioClientTransport->mDemuxerPtr != mDemuxerPtr)
        {
            RCF_THROW(ServerTransportException, "incompatible client transport")(pTcpAsioClientTransport)(typeid(*clientTransportAutoPtr));
        }
        TcpAsioClientTransport &tcpAsioClientTransport = *pTcpAsioClientTransport;
        SessionStatePtr sessionStatePtr(createSessionState());
        boost::shared_ptr<I_Session> sessionPtr(sessionStatePtr->getSessionPtr());
        sessionStatePtr->mSynchronizedSocketPtr = tcpAsioClientTransport.releaseSynchronizedSocketPtr();
        sessionStatePtr->mSynchronizedSocketPtr->setSynchronized(true);
        sessionStatePtr->mState = SessionState::WritingData;
        sessionStatePtr->onReadWrite(asio::error(0), 0);
        return sessionPtr;
    }

    ClientTransportAutoPtr TcpAsioServerTransport::createClientTransport(boost::shared_ptr<I_Session> sessionPtr)
    {
        ProactorPtr proactorPtr(sessionPtr->getProactorPtr());
        TcpAsioProactorPtr tcpAsioProactorPtr(boost::dynamic_pointer_cast<TcpAsioProactor>(proactorPtr));
        SessionStatePtr sessionStatePtr(tcpAsioProactorPtr->mSessionStateWeakPtr.lock());
        sessionStatePtr->mSynchronizedSocketPtr->setSynchronized(true);
        return ClientTransportAutoPtr( new TcpAsioClientTransport(sessionStatePtr->mSynchronizedSocketPtr, mDemuxerPtr));
    }

    bool TcpAsioServerTransport::reflect(boost::shared_ptr<I_Session> sessionPtr1, boost::shared_ptr<I_Session> sessionPtr2)
    {
        ProactorPtr proactorPtr1(sessionPtr1->getProactorPtr());
        TcpAsioProactorPtr tcpAsioProactorPtr1(boost::dynamic_pointer_cast<TcpAsioProactor>(proactorPtr1));
        SessionStatePtr sessionStatePtr1(tcpAsioProactorPtr1->mSessionStateWeakPtr.lock());

        ProactorPtr proactorPtr2(sessionPtr2->getProactorPtr());
        TcpAsioProactorPtr tcpAsioProactorPtr2(boost::dynamic_pointer_cast<TcpAsioProactor>(proactorPtr2));
        SessionStatePtr sessionStatePtr2(tcpAsioProactorPtr2->mSessionStateWeakPtr.lock());

        sessionStatePtr1->mSynchronizedSocketPtr->setSynchronized(true);
        sessionStatePtr2->mSynchronizedSocketPtr->setSynchronized(true);

        sessionStatePtr1->mReflectorSocketPtr = sessionStatePtr2->mSynchronizedSocketPtr;
        sessionStatePtr2->mReflectorSocketPtr = sessionStatePtr1->mSynchronizedSocketPtr;

        sessionStatePtr1->mReflecting = true;
        sessionStatePtr2->mReflecting = true;

        return true;
    }

    bool TcpAsioServerTransport::isConnected(boost::shared_ptr<I_Session> sessionPtr)
    {
        ProactorPtr proactorPtr(sessionPtr->getProactorPtr());
        TcpAsioProactorPtr tcpAsioProactorPtr( boost::dynamic_pointer_cast<TcpAsioProactor>(proactorPtr));
        SessionStatePtr sessionStatePtr( tcpAsioProactorPtr->mSessionStateWeakPtr.lock() );
        return sessionStatePtr.get() && sessionStatePtr->mSynchronizedSocketPtr->isConnected();
    }

    // I_Service implementation

    void TcpAsioServerTransport::open()
    {
        mInterrupt = false;
        mStopFlag = false;
        mDemuxerPtr.reset( new Demuxer );
        mCycleTimerPtr.reset( new DeadlineTimer(*mDemuxerPtr) );
        mAcceptorPtr.reset( new SocketAcceptor(*mDemuxerPtr, asio::ip::tcp::endpoint(
            asio::ip::address_v4::from_string(getNetworkInterface()),
            mPort)));

        createSessionState()->invokeAsyncAccept();
    }

    void TcpAsioServerTransport::SessionState::close()
    {
        mSynchronizedSocketPtr->close();
    }

    void TcpAsioServerTransport::close()
    {

        // cancel all outstanding async operations
        std::for_each(
            mSessionStates.begin(), 
            mSessionStates.end(), 
            boost::bind(&SessionState::close, _1));

        if (mAcceptorPtr)
        {
            mAcceptorPtr->close();
        }

        // TODO: why would we do this?
        // run the demuxer to complete all the cancelled operations
        //if (mDemuxerPtr)
        //{
        //    mDemuxerPtr->reset();
        //    mDemuxerPtr->run();
        //}

        // TODO: why is mSessionStates not empty?
        mSessionStates.clear();

        // and now we can finally destroy the asio structures
        mAcceptorPtr.reset();
        mCycleTimerPtr.reset();
        mDemuxerPtr.reset();
    }

    bool TcpAsioServerTransport::cycle(int timeoutMs, const volatile bool &stopFlag)
    {

        RCF_UNUSED_VARIABLE(stopFlag);
        RCF_ASSERT(timeoutMs >= -1);
        
        if (timeoutMs == -1)
        {
            mInterrupt = true;
        }
        else 
        {
            //timeoutMs = 1000*60;
            mCycleTimerPtr->cancel();
            mCycleTimerPtr->expires_from_now(boost::posix_time::milliseconds(timeoutMs)); // replacing timeoutMs with 1000 makes Test_Minimal work with cw...
            mCycleTimerPtr->async_wait( boost::bind(&TcpAsioServerTransport::stopCycle, this, asio::placeholders::error));
        }

        mDemuxerPtr->reset();
        mDemuxerPtr->run();

        return false;
    }

    void TcpAsioServerTransport::stopCycle(const asio::error &error)
    {
        if (!error)
        {
            mDemuxerPtr->interrupt();
        }
    }

    void TcpAsioServerTransport::stop()
    {
        mDemuxerPtr->interrupt();
    }

    void TcpAsioServerTransport::onServiceAdded(RcfServer &server)
    {
        setServer(server);
        WriteLock writeLock( getTaskEntriesMutex() );
        getTaskEntries().clear();
        getTaskEntries().push_back( 
            TaskEntry(
            boost::bind(&TcpAsioServerTransport::cycle, this, _1, _2),
            boost::bind(&TcpAsioServerTransport::stop, this)));
    }

    void TcpAsioServerTransport::onServiceRemoved(RcfServer &)
    {}

    void TcpAsioServerTransport::onServerOpen(RcfServer &)
    {
        open();
    }

    void TcpAsioServerTransport::onServerClose(RcfServer &)
    {
        close();
    }

    void TcpAsioServerTransport::onServerStart(RcfServer &)
    {
        mStopFlag = false;
    }

    void TcpAsioServerTransport::onServerStop(RcfServer &)
    {
    }

    void TcpAsioServerTransport::setServer(RcfServer &server)
    {
        pServer = &server;
    }

    RcfServer &TcpAsioServerTransport::getServer()
    {
        return *pServer;
    }

    I_SessionManager &TcpAsioServerTransport::getSessionManager()
    {
        return *pServer;
    }

    TcpAsioServerTransport::TcpAsioServerTransport(int port) :
        mDemuxerPtr(),
        mCycleTimerPtr(),
        mInterrupt(),
        mReadWriteMutexPtr( new ReadWriteMutex(ReaderPriority) ),
        mPort(port),
        mAcceptorPtr(),
        mStopFlag(),
        pServer()
    {}

    ServerTransportPtr TcpAsioServerTransport::clone() 
    { 
        return ServerTransportPtr(new TcpAsioServerTransport(mPort)); 
    }

} // namespace RCF

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)

Share

About the Author

Jarl Lindrud

Australia Australia
Software developer, ex-resident of Sweden and now living in Canberra, Australia, working on distributed C++ applications. Jarl enjoys programming, but prefers skiing and playing table tennis. He derives immense satisfaction from referring to himself in third person.

| Advertise | Privacy | Mobile
Web02 | 2.8.140814.1 | Last Updated 25 Oct 2011
Article Copyright 2005 by Jarl Lindrud
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid