Request/Reply

Request/Reply

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 core concepts.
  • You have access to Solace messaging with the following configuration details:
    • Connectivity information for a Solace 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 Cloud as outlined here. You can find other ways to get access to Solace messaging below.

Goals

The goals of this tutorial are to understand the following:

  • On the requestor side:
    1. How to create a request
    2. How to receive a response
    3. How to use the Solace API to correlate the request and response
  • On the replier side:
    1. How to detect a request expecting a reply
    2. How to generate a reply message

Get Solace Messaging

This tutorial requires access Solace messaging and requires that you know several connectivity properties about your Solace messaging. Specifically you need to know the following:

Resource Value Description
Host String This is the address clients use when connecting to the Solace messaging to send and receive messages (format: protocol://DNS_NAME:Port or protocol://IP:Port). The available protocols are ws://, wss://, http://, https://, tcp://, tcps://
Message VPN String The Solace 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)

This information will be passed as arguments to the sample scripts as described in the “Running the Samples” section below.

There are several ways you can get access to Solace Messaging and find these required properties.

Option 1: Use Solace Cloud

  • Follow these instructions to quickly spin up a cloud-based Solace 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 Web Messaging URI)
    • Message VPN
    • Client Username
    • Client Password

Option 2: Start a Solace VMR

  • Follow these instructions to start the Solace VMR in leading Clouds, Container Platforms or Hypervisors. The tutorials outline where to download and how to install the Solace VMR.
  • 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 Solace VMR “default” message VPN has authentication disabled.

Option 3: Get access to a Solace appliance

  • Contact your Solace appliance administrators and obtain the following:
    • A Solace 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

Overview

Request-reply messaging is supported by the Solace message router for all delivery modes. For direct messaging, the Solace 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 Solace 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.

Message Correlation

For request-reply messaging to be successful it must be possible for the requestor to correlate the request with the subsequent reply. Solace 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 Solace Topic where the reply should be sent. A natural choice for this is often the unique P2PINBOX_IN_USE 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 Solace 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.

Obtaining the Solace API

This tutorial depends on you having Solace Node.js API version 10 or later downloaded and available. Here are a few easy ways to get the Node.js API. The instructions in the Running the Samples section assume you’re pulling the packages from the npmjs public repository. If your environment differs then adjust the instructions appropriately.

The API Reference is available online at the Node.js API documentation.

Get the API: Using the npmjs repository

This will locate and download compatible library packages from the npmjs public repository using the local package.json specs.

npm install

Get the API: Using the Solace Developer Portal

The Solace Node.js API distribution package can be downloaded here. Install the included tar.gz tarball package named node-solclientjs-<version>.tar.gz:

npm install <path_to_tarball_directory>/node-solclientjs-<version>.tar.gz 

Trying it yourself

This tutorial is available in GitHub along with the other Solace Developer Getting Started Examples.

At the end, this tutorial walks through downloading and running the sample from source.

Implementing Request/Reply

This tutorial’s sample code comes as two separate applications: one (with the “requestor” object) send requests to a specific topic and the other (with the “replier” object) subscribes to requests on that topic, receives the requests and replies on them.

The structure of the requestor application is similar to the publish/subscribe tutorial’s topic publisher. Here instead of simply publishing a message, a request will be sent.

The structure of the replier application is similar to the topic subscriber. It differs in that when receiving the request it doesn’t only log the message but sends a reply.

The followings are exactly the same as in the publish/subscribe tutorial, refer to it for all the detailed descriptions.

  • Loading and Initializing Solace Node.js API
  • Connecting to the Solace message router
  • Session Events

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:

var requestText = 'Sample Request';
var request = solace.SolclientFactory.createMessage();
request.setDestination(solace.SolclientFactory.createTopicDestination(requestor.topicName));
request.setSdtContainer(solace.SDTField.create(solace.SDTFieldType.STRING, requestText));
request.setDeliveryMode(solace.MessageDeliveryModeType.DIRECT);

Now the request can be sent. Notice callbacks replyReceivedCb and requestFailedCb. These are functions that will be called when a reply message is received (replyReceivedCb) or sending the request fails (requestFailedCb).

try {
    requestor.session.sendRequest(
        request,
        5000, // 5 seconds timeout for this operation
        function (session, message) {
            requestor.replyReceivedCb(session, message);
        },
        function (session, event) {
            requestor.requestFailedCb(session, event);
        },
        null // not providing correlation object
    );
} catch (error) {
    requestor.log(error.toString());
}

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 request topic). The following is an example of such a reply.

replier.reply = function (message) {
    if (replier.session !== null) {
        var reply = solace.SolclientFactory.createMessage();
        var ba = message.getBinaryAttachment();
        var replyText = message.getSdtContainer().getValue() + " - Sample Reply";
        reply.setSdtContainer(solace.SDTField.create(solace.SDTFieldType.STRING, replyText));
        replier.session.sendReply(message, reply);
        replier.log('Replied.');
    } else {
        replier.log('Cannot reply: not connected to Solace message router.');
    }
};

The replier.reply is the function that is called from the replier message event listener defined for replier.session:

// define message event listener
replier.session.on(solace.SessionEventCode.MESSAGE, function (message) {
    try {
        replier.reply(message);
    } catch (error) {
        replier.log(error.toString());
    }
});

Receiving the Reply Message

All that’s left is to receive and process the reply message as it is received at the requestor or report a failure:

requestor.replyReceivedCb = function (session, message) {
	requestor.log('Received reply: "' + message.getSdtContainer().getValue() + '"');
};
requestor.requestFailedCb = function (session, event) {
	requestor.log('Request failure: ' + event.toString());
};

Summarizing

Combining the example source code shown above results in the following source code files:

Getting the Source

Clone the GitHub repository containing the Solace samples.

git clone https://github.com/SolaceSamples/solace-samples-nodejs
cd solace-samples-nodejs

Note: the code in the master branch of this repository depends on Solace Node.js API version 10 or later. If you want to work with an older version clone the branch that corresponds your version.

Installing the Node.js API

For a local installation of the API package, run from the current https:dev.solace.comsamplessolace-samples-nodejs directory:

npm install

Running the Samples

The samples consist of two separate requestor and replier Node.js applications in the /src/basic-samples directory: (BasicRequestor.js and BasicReplier.js).

The publisher application publishes one message and exits, the subscriber application is running until Ctrl-C is pressed on the console.

Sample Output

First run BasicReplier.js in Node.js, giving it following arguments:

node _BasicReplier.js <host:port> <client-username> <client-password> <message-vpn>

The following is the output of the tutorial’s BasicReplier.js application after it successfully connected to the Solace message router and subscribed to the request topic.

$ node BasicReplier.js ws://192.168.133.64 testuser@default passw
[14:52:10]
*** replier to topic "tutorial/topic" is ready to connect ***
[14:52:10] Connecting to Solace message router using url: ws://192.168.133.64
[14:52:10] Client username: testuser
[14:52:10] Solace message router VPN name: default
[14:52:10] Press Ctrl-C to exit
[14:52:10] === Successfully connected and ready to subscribe to request topic. ===
[14:52:10] Subscribing to topic: tutorial/topic
[14:52:10] Successfully subscribed to request topic: tutorial/topic
[14:52:10] === Ready to receive requests. ===

Now, run BasicRequestor.js in Node.js, also specifying the same arguments.

It will connect to the router, send a request, receive a reply and exit.

The following is the output of the tutorial’s BasicRequestor.js application after it successfully connected to the Solace message router, sent a request, received a reply and exited.

$ node BasicRequestor.js ws://192.168.133.64 testuser@default passw
[14:52:16]
*** requestor to topic "tutorial/topic" is ready to connect ***
[14:52:16] Connecting to Solace message router using url: ws://192.168.133.64
[14:52:16] Client username: testuser
[14:52:16] Solace message router VPN name: default
[14:52:16] === Successfully connected and ready to send requests. ===
[14:52:16] Sending request "Sample Request" to topic "tutorial/topic"...
[14:52:16] Received reply: "Sample Request - Sample Reply", details:
Destination:                            [Topic #P2P/v:vmr-133-64/GJxznbpz/solclientjs/nodejs/0623304208/0001/#]
CorrelationId:                          #REQ1
Class Of Service:                       COS1
DeliveryMode:                           DIRECT
Expiration:                             0 (Wed Dec 31 1969 19:00:00 GMT-0500 (Eastern Standard Time))
Reply Message
Binary Attachment:                      len=32
  1c 20 53 61 6d 70 6c 65    20 52 65 71 75 65 73 74    ..Sample.Request
  20 2d 20 53 61 6d 70 6c    65 20 52 65 70 6c 79 00    .-.Sample.Reply.

[14:52:16] Disconnecting from Solace message router...
[14:52:16] Disconnected.

This is the replier replying to a request (BasicReplier.js):

[14:52:16] Received message: "Sample Request", details:
Destination:                            [Topic tutorial/topic]
CorrelationId:                          #REQ1
Class Of Service:                       COS1
DeliveryMode:                           DIRECT
Expiration:                             0 (Wed Dec 31 1969 19:00:00 GMT-0500 (Eastern Standard Time))
ReplyTo:                                [Topic #P2P/v:vmr-133-64/GJxznbpz/solclientjs/nodejs/0623304208/0001/#]
Binary Attachment:                      len=17
  1c 11 53 61 6d 70 6c 65    20 52 65 71 75 65 73 74    ..Sample.Request
  00                                                    .

[14:52:16] Replying...
[14:52:16] Replied.

With that you now know how to successfully implement the request-reply message exchange pattern using Direct messages.

If you have any issues sending and replying a message, check the Solace community Q&A for answers to common issues seen.