Request/Reply
10 Minute Read
This tutorial outlines both roles in the request-response message exchange pattern. It will show you how to act as the client by creating a request, sending it and waiting for the response. It will also show you how to act as the server by receiving incoming requests, creating a reply and sending it back to the client. It builds on the basic concepts introduced in publish/subscribe tutorial.
Assumptions
This tutorial assumes the following:
- You are familiar with Solace PubSub+ core concepts.
- You have access to PubSub+ messaging with the following configuration details:
- Connectivity information for a PubSub+ message-VPN
- Enabled client username and password
One simple way to get access to Solace messaging quickly is to create a messaging service in Solace PubSub+ Cloud as outlined here. You can find other ways to get access to PubSub+ messaging below.
The build instructions in this tutorial assume you are using a Linux shell. If your environment differs, adapt the instructions.
Goals
The goal of this tutorial is to understand the following:
- On the requestor side:
- How to create a request
- How to receive a response
- How to use the Solace PubSub+ API to correlate the request and response
- On the replier side:
- How to detect a request expecting a reply
- How to generate a reply message
Overview
Request-reply messaging is supported by the PubSub+ message router for all delivery modes. For direct messaging, the Solace PubSub+ APIs provide the Requestor object for convenience. This object makes it easy to send a request and wait for the reply message. It is a convenience object that makes use of the API provided “inbox” topic that is automatically created for each PubSub+ client and automatically correlates requests with replies using the message correlation ID. (See Message Correlation below for more details). On the reply side another convenience method enables applications to easily send replies for specific requests. Direct messaging request reply is the delivery mode that is illustrated in this sample.
It is also possible to use guaranteed messaging for request reply scenarios. In this case the replier can listen on a queue for incoming requests and the requestor can use a temporary endpoint to attract replies. The requestor and replier must manually correlate the messages. This is explained further in the Solace PubSub+ documentation and shown in the API samples named RRGuaranteedRequestor
and RRGuaranteedReplier
.
Message Correlation
For request-reply messaging to be successful it must be possible for the requestor to correlate the request with the subsequent reply. PubSub+ messages support two fields that are needed to enable request-reply correlation. The reply-to field can be used by the requestor to indicate a PubSub+ Topic or Queue where the reply should be sent. A natural choice for this is often the unique P2PInboxInUse
topic which is an auto-generated unique topic per client which is accessible as a session property. The second requirement is to be able to detect the reply message from the stream of incoming messages. This is accomplished using the correlation-id field. This field will transit the PubSub+ messaging system unmodified. Repliers can include the same correlation-id in a reply message to allow the requestor to detect the corresponding reply. The figure below outlines this exchange.
For direct messages however, this is simplified through the use of the Requestor
object as shown in this sample.
Get Solace Messaging
This tutorial requires access Solace PubSub+ messaging and requires that you know several connectivity properties about your Solace messaging. Specifically you need to know the following:
Resources | Value | Description |
---|---|---|
Host | String | This is the address clients use when connecting to the PubSub+ messaging to send and receive messages. (Format: DNS_NAME:Port or IP:Port ) |
Message VPN | String | The PubSub+ message router Message VPN that this client should connect to. |
Client Username | String | The client username. (See Notes below) |
Client Password | String | The client password. (See Notes below) |
There are several ways you can get access to PubSub+ Messaging and find these required properties.
Option 1: Use PubSub+ Cloud
-
Follow these instructions to quickly spin up a cloud-based PubSub+ messaging service for your applications.
-
The messaging connectivity information is found in the service details in the connectivity tab (shown below). You will need:
- Host:Port (use the SMF URI)
- Message VPN
- Client Username
- Client Password
Option 2: Start a PubSub+ Software
-
Follow these instructions to start the PubSub+ Software in leading Clouds, Container Platforms or Hypervisors. The tutorials outline where to download and how to install the PubSub+ Software.
-
The messaging connectivity information are the following:
-
Host: <public_ip> (IP address assigned to the VMR in tutorial instructions)
-
Message VPN: default
-
Client Username: sampleUser (can be any value)
-
Client Password: samplePassword (can be any value)
Note: By default, the PubSub+ Software "default" message VPN has authentication disabled.
-
Option 3: Get access to a PubSub+ Appliance
-
Contact your PubSub+ appliance administrators and obtain the following:
- A PubSub+ Message-VPN where you can produce and consume direct and persistent messages
- The host name or IP address of the Solace appliance hosting your Message-VPN
- A username and password to access the Solace appliance
Obtaining the Solace PubSub+ API
The repository where this tutorial reside already comes with C API library version 7.7.1.4. However, you should always check for any newer version for download here. The C API is distributed as a gzipped tar file for all supported platform. To update to a newer version of the API, please ensure that the existing core library components are appropriately replaced by the newer components.
Connecting to the Solace PubSub+ message router
In order to send or receive messages, an application must connect a PubSub+ session. The PubSub+ session is the basis for all client communication with the PubSub+ message router.
In the Solace messaging API for C (SolClient), a few distinct steps are required to create and connect a Solace session.
- The API must be initialized
- Appropriate asynchronous callbacks must be declared
- A SolClient Context is needed to control application threading
- The SolClient session must be created
Initializing the CCSMP API
To initialize the SolClient API, you call the initialize method with arguments that control logging.
/* solClient needs to be initialized before any other API calls. */
solClient_initialize ( SOLCLIENT_LOG_DEFAULT_FILTER, NULL );
This call must be made prior to making any other calls to the SolClient API. It allows the API to initialize internal state and buffer pools.
SolClient Asynchronous Callbacks
The SolClient API is predominantly an asynchronous API designed for the highest speed and lowest latency. As such most events and notifications occur through callbacks. In order to get up and running, the following basic callbacks are required at a minimum.
static int msgCount = 0;
solClient_rxMsgCallback_returnCode_t
sessionMessageReceiveCallback ( solClient_opaqueSession_pt opaqueSession_p, solClient_opaqueMsg_pt msg_p, void *user_p )
{
printf ( "Received message:\n" );
solClient_msg_dump ( msg_p, NULL, 0 );
printf ( "\n" );
msgCount++;
return SOLCLIENT_CALLBACK_OK;
}
void
sessionEventCallback ( solClient_opaqueSession_pt opaqueSession_p,
solClient_session_eventCallbackInfo_pt eventInfo_p, void *user_p )
{
printf("Session EventCallback() called: %s\n", solClient_session_eventToString ( eventInfo_p->sessionEvent));
}
The messageReceiveCallback is invoked for each message received by the Session. In this sample, the message is printed to the screen.
The eventCallback is invoked for various significant session events like connection, disconnection, and other SolClient session events. In this sample, simply prints the events. See the SolClient API documentation and samples for details on the session events.
Context Creation
As outlined in the core concepts, the context object is used to control threading that drives network I/O and message delivery and acts as containers for sessions. The easiest way to create a context is to use the context initializer with default thread creation.
/* Context */
solClient_opaqueContext_pt context_p;
solClient_context_createFuncInfo_t contextFuncInfo = SOLCLIENT_CONTEXT_CREATEFUNC_INITIALIZER;
solClient_context_create ( SOLCLIENT_CONTEXT_PROPS_DEFAULT_WITH_CREATE_THREAD,
&context_p, &contextFuncInfo, sizeof ( contextFuncInfo ) );
Session Creation
Finally a session is needed to actually connect to the PubSub+ message router. This is accomplished by creating a properties array and connecting the session.
/* Session */
solClient_opaqueSession_pt session_p;
solClient_session_createFuncInfo_t sessionFuncInfo = SOLCLIENT_SESSION_CREATEFUNC_INITIALIZER;
/* Session Properties */
const char *sessionProps[50] = {0, };
int propIndex = 0;
char *username,*password,*vpnname,*host;
/* Configure the Session function information. */
sessionFuncInfo.rxMsgInfo.callback_p = sessionMessageReceiveCallback;
sessionFuncInfo.rxMsgInfo.user_p = NULL;
sessionFuncInfo.eventInfo.callback_p = sessionEventCallback;
sessionFuncInfo.eventInfo.user_p = NULL;
/* Configure the Session properties. */
propIndex = 0;
host = argv[1];
vpnname = argv[2];
username = strsep(&vpnname,"@");
password = argv[3];
sessionProps[propIndex++] = SOLCLIENT_SESSION_PROP_HOST;
sessionProps[propIndex++] = host;
sessionProps[propIndex++] = SOLCLIENT_SESSION_PROP_VPN_NAME;
sessionProps[propIndex++] = vpnname;
sessionProps[propIndex++] = SOLCLIENT_SESSION_PROP_USERNAME;
sessionProps[propIndex++] = username;
sessionProps[propIndex++] = SOLCLIENT_SESSION_PROP_PASSWORD;
sessionProps[propIndex++] = password;
sessionProps[propIndex++] = NULL;
/* Create the Session. */
solClient_session_create ( ( char ** ) sessionProps,
context_p,
&session_p, &sessionFuncInfo, sizeof ( sessionFuncInfo ) );
/* Connect the Session. */
solClient_session_connect ( session_p );
printf ( "Connected.\n" );
When creating the session, the factory method takes the session properties, the session pointer and information about the session callback functions. The API then creates the session within the supplied context and returns a reference in the session pointer. The final call to solClient_session_connect establishes the connection to the PubSub+ message router which makes the session ready for use.
At this point your client is connected to the PubSub+ message router. You can use PubSub+ Manager to view the client connection and related details.
Making a request
First let’s look at the requestor. This is the application that will send the initial request message and wait for the reply.
The requestor must create a message and the topic to send the message to:
solClient_destination_t destination;
/* Set the destination Topic for the request message. */
destination.destType = SOLCLIENT_TOPIC_DESTINATION;
destination.dest = "topic/topic1";
if ( ( rc = solClient_msg_setDestination ( msg_p, &destination, sizeof ( destination ) ) ) == SOLCLIENT_OK )
{
/* Create a stream in the binary attachment part of the message. */
solClient_msg_createBinaryAttachmentStream ( msg_p, &stream_p, 100 );
//Go ahead and add data into the binary stream.
}
Now the request can be sent. This example demonstrates a blocking call where the method will wait for the response message to be received.
solClient_opaqueMsg_pt replyMsg_p;
int timeout = 5000; //5 sec
if (solClient_session_sendRequest ( opaqueSession_p,msg_p, &replyMsg_p, timeout) == SOLCLIENT_OK)
{
//proceed to extract reply result
}
If the call request was executed successfully then the returned return code is SOLCLIENT_OK
.
If the timeout is set to zero then the solClient_session_sendRequest
call becomes non-blocking and it returns immediately.
Replying to a request
Now it is time to receive the request and generate an appropriate reply.
Just as with previous tutorials, you still need to connect a session and subscribe to the topics that requests are sent on. The following is an example of such reply.
static solClient_rxMsgCallback_returnCode_t;
requestMsgReceiveCallback ( solClient_opaqueSession_pt opaqueSession_p, solClient_opaqueMsg_pt msg_p, void *user_p )
{
solClient_returnCode_t rc = SOLCLIENT_OK;
solClient_opaqueMsg_pt replyMsg_p;
solClient_opaqueContainer_pt stream_p;
solClient_opaqueContainer_pt replyStream_p;
double result;
if ( ( rc = solClient_msg_getBinaryAttachmentStream ( msg_p, &stream_p ) ) == SOLCLIENT_OK )
{
//extract binary data from stream
}
//Proceed to create a reply
solClient_msg_alloc ( &replyMsg_p );
if ( ( rc = solClient_msg_createBinaryAttachmentStream ( replyMsg_p, &replyStream_p, 32 ) ) == SOLCLIENT_OK )
{
//insert binary data as reply
//Send reply
solClient_session_sendReply ( opaqueSession_p, msg_p, replyMsg_p );
}
}
The requestMsgReceiveCallback
function in this case replace the implementation of the sessionMessageReceiveCallback
, which is passed as parameter in solClient_session_create
.
Receiving the Reply Message
All that’s left is to receive and process the reply message as it is received at the requestor. If you now update your requestor code to match the following you will see each reply printed to the console.
if (solClient_session_sendRequest ( opaqueSession_p,msg_p, &replyMsg_p, timeout) == SOLCLIENT_OK)
{
//proceed to extract reply result
if ( solClient_msg_getBinaryAttachmentStream ( replyMsg_p, &replyStream_p ) == SOLCLIENT_OK )
{
//extract data from binary stream
}
}
solClient_msg_free ( &replyMsg_p );
Summarizing
The full source code for this example is available in GitHub. If you combine the example source code shown above results in the following source:
Building
Building these examples is simple.
For linux and mac
All you need is to execute the compile script in the build
folder.
linux
build$ ./build_intro_linux_xxx.sh
mac
build$ ./build_intro_mac_xxx.sh
For windows
You can either build the examples from DOS prompt or from Visual Studio IDE.
To build from DOS prompt, you must first launch the appropriate Visual Studio Command Prompt and then run the batch file
c:\solace-sample-c\build>build_intro_win_xxx.bat
Referencing the downloaded SolClient library include and lib file is required. For more advanced build control, consider adapting the makefile found in the "intro" directory of the SolClient package. The above samples very closely mirror the samples found there.
Running the Samples
First start the BasicReplier
so that it is up and listening for requests. Then you can use the BasicRequestor
sample to send requests and receive replies. Pass your PubSub+ messaging router connection properties as parameters.
bin$ . ./setenv.sh
bin$ ./BasicReplier -u <client-username>@<message-vpn> -c <protocol>://<msg_backbone_ip>:<port> -p <password> -t <topic>
Sending request for 9 PLUS 5
Received reply message, result = 14.000000
Sending request for 9 MINUS 5
Received reply message, result = 4.000000
Sending request for 9 TIMES 5
Received reply message, result = 45.000000
Sending request for 9 DIVIDED_BY 5
Received reply message, result = 1.800000
bin$ ./BasicRequestor -u <client-username>@<message-vpn> -c <protocol>://<msg_backbone_ip>:<port> -p <password> -t <topic>
Sending request for 9 PLUS 5
Received reply message, result = 14.000000
Sending request for 9 MINUS 5
Received reply message, result = 4.000000
Sending request for 9 TIMES 5
Received reply message, result = 45.000000
Sending request for 9 DIVIDED_BY 5
Received reply message, result = 1.800000
With that you now know how to successfully implement the request-reply message exchange pattern using Direct messages.