A JMS C# Topic Publisher

Introduction

This example demonstrates how you can publish messages to a JMS Topic from a .NET application written in C#. Asynchronous messaging is very much a peer-to-peer technology that can make it hard to distinguish between client and server usage. Your published messages could be client replies or they could be server publications, it totally depends on your application.

In this example, we're publishing stock quotes using two different message types: a TextMessage and a MapMessage. We use two different message types solely for the purpose of illustrating something other than TextMessages. In a real production application you would probably use one message type and save yourself message type checks and conditional casts. Please also see the corresponding C# Topic Subscriber example as well as the platform-portable C++ examples.

The example relies on JuggerNET-generated .NET bindings for the JMS API. In the JMS Courier product, the JMS.NET bindings are bundled into an easy-to-use .NET assembly that does not require you to use the code generator.

The source code

The following block contains the full application except for the Example.InitJvm() procedure, which parses command line arguments and sets up some system properties based on command line input and a configuration file.

using java.lang;
using javax.naming;
using javax.jms;
using Codemesh.JuggerNET;
using System;
using System.Threading;


///
/// @brief The quote publisher example
///
/// This is a heavily documented example that illustrates how to
/// publish stock quotes to a topic via the JMS Courier .NET APIs.
///
public class Application
{
    public static void Main(string[] args)
    {
        if( args.Length < 1 )
        {
            Console.Error.WriteLine( "Usage: quotepub [tickersymbol]+" );
            Console.Error.WriteLine( "Usage: quotepub CDMSH AAPL MSFT" );
            Environment.Exit( 1 );
        }

        try
        {
            // set up the Java runtime environment (defined in 'Example.cs')
            //
            // This function has to at least initialize
            // - the classpath, 
            // - the JVM path (unless you wish to rely on a default JVM we might or might not find),
            // - the JNDI properties
            // - lookup names
            //
            // We also set up the JMS JNDI properties in this method.
            //
            // You can perform these steps in code or rely on a configuration file,
            // it's up to you.  All these cases are documented in the 'rtconfig' examples.
            //
            Example.InitJvm( args );

            // the JNDI properties are assumed to be set up correctly at this point;
            // That all happens in the InitJvm() function, WHICH IS EXAMPLE CODE AND
            // DOES NOT MEAN THAT YOU HAVE TO DO THINGS THIS WAY!
            InitialContext            ictx = new InitialContext();

            // The .NET examples assume that the TopicConnectionFactory lookup name is in the system
            // properties at this point.  That all happens in the InitJvm() function, WHICH IS 
            // EXAMPLE CODE AND DOES NOT MEAN THAT YOU HAVE TO DO THINGS THIS WAY!
            // We look for the property "TCF" and give it the default value "TopicConnectionFactory" 
            // if we can't find it.
            string                    tcfName = java.lang.System.getProperty( "TCF", "TopicConnectionFactory" );
            TopicConnectionFactory    tcf = TopicConnectionFactoryImpl.From( ictx.lookup( tcfName ) );
        
            if ( tcf == null )
            {
                Console.Error.WriteLine( "TCF not found for lookup name '{0}'", tcfName );
                Environment.Exit( -1 );              
            }

            // create a topic connection
            // topic connections are relatively heavy objects, so don't create more than one
            // unless you know that you really have to.  It's better to work with multiple 
            // sessions instead.
            TopicConnection           tc = tcf.createTopicConnection();

            // create a session in which we publish (non-transacted, auto-acknowledging)
            // a session should never be shared by more than one thread. If you have more than
            // one thread you need more than one session.
            TopicSession              ts = tc.createTopicSession( false, SessionImpl.AUTO_ACKNOWLEDGE );

            // look up the topic name we want to use (set up in 'InitJvm')
            string                    topicName = java.lang.System.getProperty( "TOPIC", "testTopic" );
            Topic                     topic = TopicImpl.From( ictx.lookup( topicName ) );

            // create the publisher for that topic
            TopicPublisher            tp = ts.createPublisher( topic );

            Console.WriteLine( "Starting to publish quotes to topic '{0}'", topicName );
            Console.WriteLine( "Hit <ENTER> to quit..." );

            // here comes the business logic...

            // seed the random number generator
            Random      random = new Random();

            // set up the ticker symbols and quotes
            int                       numSymbols = args.Length;
            String[]                  symbols = args;
            double[]                  values = new double[ numSymbols ];

            for( int i=0; i<numSymbols; i++ )
            {
                // a random starting value
                values[ i ] = random.NextDouble() * 100;
            }

            tc.start();

            while( !NativeInterface.Kbhit() )
            {
                // we randomly pick whether or not we send MapMessages or TextMessages
                bool    bSendMapMsg = ( random.Next( 2 ) == 1 );

                if( bSendMapMsg )
                {
                    // if we picked map messages, we have the session create one
                    MapMessage        msg = ts.createMapMessage();

                    // for every stock symbol, calculate a random price 
                    for( int i=0; i<numSymbols; i++ )
                    {
                        msg.setDouble( symbols[ i ], values[ i ] );
                        values[ i ] += ( random.NextDouble() * 2 - 1 );
                    }

                    tp.publish( msg, DeliveryModeImpl.NON_PERSISTENT, 1, 5 );
                    Console.WriteLine( "Published map message: {0}", msg.ToString() );
                }
                else
                {
                    TextMessage        msg = ts.createTextMessage();

                    for( int i=0; i<numSymbols; i++ )
                    {
                        msg.setStringProperty( "SYMBOL", symbols[ i ] );
                        msg.setText( values[ i ].ToString() );
                        values[ i ] += ( random.NextDouble() * 2 - 1 );

                        tp.publish( msg, DeliveryModeImpl.NON_PERSISTENT, 1, 5 );
                        Console.WriteLine( "Published text message: {0}={1}", symbols[ i ], msg.ToString() );
                    }
                }

                // random delay of up to 500ms
                Thread.Sleep( new TimeSpan( random.Next( 5000000 ) ) );
            }

            // orderly shutdown processing
            tc.stop();
            ts.close();
            tc.close();

            Console.WriteLine( "Done publishing!" );

            return;
        }
        // you can write hierarchical exception catch blocks, just like in Java
        // and you have full access to the entire exception information and
        // functionality
        catch( NamingException nex )
        {
            Console.Error.WriteLine( "JNDI Naming Exception: {0}", nex.ToString() );
            
            Environment.Exit( -1 );
        }
        catch( System.Exception e )
        {
            Console.Error.WriteLine( "Exception: {0}", e.ToString() );
            
            Environment.Exit( -1 );
        }
    }
}


Copyright 2006-2011 by Codemesh, Inc., ALL RIGHTS RESERVED

:
jms c# topic publisher
home products support customers partners newsroom about us contact us