Publish/Subscribe

Publish/Subscribe

This tutorial will introduce you to the fundamentals of the Solace API by connecting a client, adding a topic subscription and sending a message matching this topic subscription. This forms the basis for any publish / subscribe message exchange illustrated here:

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 goal of this tutorial is to demonstrate the most basic messaging interaction using Solace. This tutorial will show you:

  1. How to build and send a message on a topic
  2. How to subscribe to a topic and receive a 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: DNS_NAME:Port or IP:Port)
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)

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 SMF 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

Obtaining the Solace API

This tutorial depends on you having the Solace Messaging API for C#/.NET (also referred to as SolClient for .NET) downloaded and installed for your project, and the instructions in this tutorial assume you successfully done it. If your environment differs then adjust the build instructions appropriately.

Here are a few easy ways to get this API.

Get the API: Using nuget.org

Use the NuGet console or the NuGet Visual Studio Extension to download the SolaceSystems.Solclient.Messaging package for your solution and to install it for your project.

The package contains the required libraries and brief API documentation. It will automatically copy correct libraries from the package to the target directory at build time, but of course if you compile your program from the command line you would need to refer to the API assemblies and libraries locations explicitly.

Notice that in this case both x64 and x86 API assemblies and libraries have the same names.

Get the API: Using the Solace Developer Portal

The SolClient for .NET can be downloaded here. That distribution is a zip file containing the required libraries, detailed API documentation, and examples.

You would need either to update your Visual Studio project to point to the extracted assemblies and libraries, or to refer to their locations explicitly.

Notice that in this case x64 and x86 API assemblies and libraries have different names, e.g. the x86 API assembly is SolaceSystems.Solclient.Messaging.dll and the x64 API assembly is SolaceSystems.Solclient.Messaging_64.dll.

For the purposes of this tutorial, you will connect to the default message VPN of a Solace VMR so the only required information to proceed is the Solace VMR host string which this tutorial accepts as an argument.

Connecting to the Solace message router

In order to send or receive messages, an application must connect a Solace session. The Solace session is the basis for all client communication with the Solace message router.

In the Solace messaging API for C# (CSCSMP) before using the API, the ContextFactory must be initialized. This allows the API to initialize required state, threads, and logging. The ContextFactory is initialized with a set of ContextFactoryProperties.

ContextFactoryProperties cfp = new ContextFactoryProperties()
{
SolClientLogLevel = SolLogLevel.Warning
};
cfp.LogToConsoleError();
ContextFactory.Instance.Init(cfp);

Then the ContextFactory instance can be used to create the context IContext (see API concepts) that is used to create Solace sessions (ISession) from a set of SessionProperties.

Notice the optional HandleMessage parameter in the CreateSession call. This is the message consumer. It needs to be present only for receiving a message (see details on how to receive a message in the next section of this tutorial).

SessionProperties sessionProps = new SessionProperties()
{
    Host = host,
    VPNName = VPNName,
    UserName = UserName,
    Password = Password,
    ReconnectRetries = DefaultReconnectRetries
};

Console.WriteLine("Connecting as {0}@{1} on {2}...", UserName, VPNName, host);

using (IContext context =
                ContextFactory.Instance.CreateContext(new ContextProperties(), null))
using (ISession session = context.CreateSession(sessionProps, HandleMessage, null))
{
    ReturnCode returnCode = session.Connect();
    if (returnCode == ReturnCode.SOLCLIENT_OK)
    {
        // connected to the Solace message router
    }
}

At this point your client is connected to the Solace message router. You can use SolAdmin to view the client connection and related details.

Receiving a message

This tutorial uses “Direct” messages which are at most once delivery messages. So first, let’s express interest in the messages by subscribing to a Solace topic. Then you can look at publishing a matching message and see it received.

With a session connected in the previous step, the next step is to create a message consumer. Message consumers enable the asynchronous receipt of messages through callbacks. These callbacks are defined in CSCSMP by the message receive delegate.

private void HandleMessage(object source, MessageEventArgs args)
{
    Console.WriteLine("Received published message.");
    // Received a message
    using (IMessage message = args.Message)
    {
        // Expecting the message content as a binary attachment
        Console.WriteLine("Message content: {0}", Encoding.ASCII.GetString(message.BinaryAttachment));
        // finish the program
        WaitEventWaitHandle.Set();
    }
}

The message consumer code uses an event wait handle in this example to release the blocked main thread when a single message has been received.

You must subscribe to a topic in order to express interest in receiving messages. This tutorial uses the topic “tutorial/topic”.

ReturnCode returnCode = Session.Connect();
if (returnCode == ReturnCode.SOLCLIENT_OK)
{
    Console.WriteLine("Session successfully connected.");

    Session.Subscribe(ContextFactory.Instance.CreateTopic("tutorial/topic"), true);

    Console.WriteLine("Waiting for a message to be published...");
    WaitEventWaitHandle.WaitOne();
}

Then after the subscription is added, the consumer is started. At this point the consumer is ready to receive messages and the main thread is blocked until a message is received.

WaitEventWaitHandle.WaitOne();

Sending a message

Now it is time to send a message to the waiting consumer.

Creating and sending the message

To send a message, you must create a message and a topic. Both of these are created from the ContextFactory. This tutorial will send a Solace message with Text contents “Sample Message”.

using (IMessage message = ContextFactory.Instance.CreateMessage())
{
    message.Destination = ContextFactory.Instance.CreateTopic("tutorial/topic");
    message.BinaryAttachment = Encoding.ASCII.GetBytes("Sample Message");

    Console.WriteLine("Publishing message...");
    ReturnCode returnCode = session.Send(message);
    if (returnCode == ReturnCode.SOLCLIENT_OK)
    {
        Console.WriteLine("Done.");
    }
    else
    {
        Console.WriteLine("Publishing failed, return code: {0}", returnCode);
    }
}

At this point a message to the Solace message router has been sent and your waiting consumer will have received the message and printed its contents to the screen.

Summarizing

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

Building

Build it from Microsoft Visual Studio or command line:

> csc /reference:SolaceSystems.Solclient.Messaging_64.dll /optimize /out:TopicPublisher.exe  TopicPublisher.cs
> csc /reference:SolaceSystems.Solclient.Messaging_64.dll /optimize /out:TopicSubscriber.exe  TopicSubscriber.cs

You need SolaceSystems.Solclient.Messaging_64.dll (or SolaceSystems.Solclient.Messaging.dll) at compile and runtime time and libsolclient.dll at runtime in the same directory where your source and executables are.

Both DLLs are part of the Solace C#/.NET API distribution and located in solclient-dotnet\lib directory of that distribution.

Sample Output

First start the TopicSubscriber.exe so that it is up and waiting for published messages. Then you can use the TopicPublisher.exe sample to publish a message. Pass your Solace messaging router connection properties as parameters.

$ ./TopicSubscriber <host> <username>@<vpnname> <password>
Connecting as <username>@<vpnname> on <host>...
Session successfully connected.
Waiting for a message to be published...
Received published message.
Message content: Sample Message
Finished.
$ ./TopicPublisher <host> <username>@<vpnname> <password>
Connecting as <username>@<vpnname> on <host>...
Session successfully connected.
Publishing message...
Done.
Finished.

With that you now know how to successfully implement publish-subscribe message exchange pattern using Direct messages.

If you have any issues publishing and receiving a message, check the Solace community for answers to common issues seen.