ObjectQ - Overview - simClient.c

simAgent_c.c

#include "cpTransMgr.h"
#include "simAgent.h"

extern void error(const String& errMsg, cpStatus ret);

// Constructors
simAgent::simAgent() 
{
    cpStatus ret;

    if ((ret = cpDispatch->registerServer(AserviceName, this)) != cpSUCCESS)
        error("Server registration failed", ret);
}

simAgent::simAgent(const String& s)  : cpAgent()
{
    AserviceName = s;
    cpStatus ret;

    if ((ret = cpDispatch->registerServer(AserviceName, this)) != cpSUCCESS)
        error("Server registration failed", ret);
}

// Destructor
simAgent::~simAgent()
{
    cpDispatch->unregisterServer(AserviceName, this);
}

// Mark the agent as available to handle the next request
cpStatus
simAgent::makeAvailable()
{
    cpStatus ret;

    if ((ret = cpDispatch->serverAvailable(AserviceName, this)) != cpSUCCESS)
        error("Server availability failed", ret);
    return ret;
}

// This function is invoked by the dispatcher when
// an incoming request is received
cpStatus
simAgent::requestHandler(cpEnvelope *env)
{
    cpStatus ret;
    cpResource res;
    cpTransport *t;
    cpGetReqMessage reqMsg;

    // Pull out the next message
    if ((ret = env->nextMessage(reqMsg)) != cpSUCCESS) {
        error("Message retrieval failed", ret);
        return ret;
    }

    // Display the instance name
    cout << "Request: <" << reqMsg.instanceId() << "> " << endl;

    // Construct a response message
    cpGetRespMessage respMsg;
    respMsg.instanceId("Goodbye World!");

    // Put it into an envelope
    env->clearMessages();
    if ((ret = env->addMessage(respMsg)) != cpSUCCESS) {
        (void)makeAvailable();
        error("Message add failed", ret);
        return ret;
    }
    env->last();

    // Send it back
    if ((t = cpXportMgr->transport(AserviceName)) == 0) {
        (void)makeAvailable();
        error("Get transport failed", cpFAIL);
        return ret;
    }
    if ((ret = t->reply(*env)) != cpSUCCESS) {
        (void)makeAvailable();
        error("Reply failed", ret);
        return ret;
    }

    // We're available again
    (void)makeAvailable();

    return cpSUCCESS;
}