Re.Mark

Messaging with .NET and ActiveMQ

You’ve probably heard of Java Message Service (JMS). It’s a standard Java API for creating, sending, receiving and reading messages. ActiveMQ, an Apache project, is an open source message broker that supports JMS 1.1. In addition to supporting JMS, it supports other protocols that allow clients to be written in a variety of languages. Look at this page for more information. Sounds good, doesn’t it? Let’s try it out using .NET, C# and Visual Studio 2005.

Download and install the JDK

ActiveMQ is written in Java, so you’ll need a Java Runtime Environment (JRE) to be able to run it. The Java Development Kit (JDK) comes with extra utilities that you’ll find useful later on. I used the Java Development Kit SE 6 update 1, which you can find here.

Download and install ActiveMQ

Get the latest release of ActiveMQ from the downloads section. I used version 4.1.1. Once you have downloaded the zip file, extract the contents to a suitable folder. To test the installation, open a command prompt and use the cd command to set the current folder to be the installation folder (in which you extracted the ActiveMQ files.) Then type the following command:

bin\activemq

All being well, you should see a number of lines of information – the last of which should be something like:

INFO  ActiveMQ JMS Message Broker (localhost, ID:your-PC-51222-1140729837569-0:0) has started

The installation notes on the ActiveMQ site point out that there are working directories that get created relative to the current working folder. This means that for ActiveMQ to work correctly, you must start it from the installation folder. To double check, start a new command prompt and type the following command:

netstat -an|find "61616"

The response should be something like the following:

  TCP    0.0.0.0:61616          0.0.0.0:0              LISTENING

When you want to stop ActiveMQ, enter <CTRL+C>. For now leave it running.

Download Spring.Messaging.NMS

NMS is the .NET Messaging API. Spring .NET has a messaging library built on NMS. It’s under development, but you can get it here. I used version 20070320-1632. Extract the files from the zip file to somewhere sensible.

The Listener

Create a new console application. I called mine ListenerConsole. You need to add 4 references:

  1. Spring.Core
  2. ActiveMQ
  3. NMS
  4. Spring.Messaging.NMS

These dlls can all be found in the bin\net\2.0\debug folder of Spring.Messaging.NMS. Here’s the code for the Program class in the listener console:

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

using ActiveMQ;
using Spring.Messaging.Nms;
using Spring.Messaging.Nms.Listener;

namespace ListenerConsole
{
    class Program
    {
        private const string URI = "tcp://localhost:61616";
        private const string DESTINATION = "test.queue";

        static void Main(string[] args)
        {
            try
            {
                ConnectionFactory connectionFactory = new ConnectionFactory(URI);

                using (SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer())
                {
                    listenerContainer.ConnectionFactory = connectionFactory;
                    listenerContainer.DestinationName = DESTINATION;
                    listenerContainer.MessageListener = new Listener();
                    listenerContainer.AfterPropertiesSet();
                    Console.WriteLine("Listener started.");
                    Console.WriteLine("Press <ENTER> to exit.");
                    Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.WriteLine("Press <ENTER> to exit.");
                Console.Read();
            }

        }
    }
}

The interesting part of the code is the creation and set up of the SimpleMessageListenerContainer. ConnectionFactory is from the ActiveMQ namespace and implements the IConnectionFactory interface defined in NMS. The Uri of the message broker is passed to the constructor. SimpleMessageListenerContainer is part of Spring.Messaging.NMS (in the Listener namespace.) Note that SimpleMessageListenerContainer implements IDisposable. The missing part of this puzzle is the Listener class. Create a new class in the project, call it Listener and insert the following code:

using System;
using Spring.Messaging.Nms;
using NMS;
namespace ListenerConsole
{
    class Listener : IMessageListener
    {
        public Listener()
        {
            Console.WriteLine("Listener created.rn");
        }
        #region IMessageListener Members

        public void OnMessage(NMS.IMessage message)
        {
            ITextMessage textMessage = message as ITextMessage;
            Console.WriteLine(textMessage.Text);
        }

        #endregion
    }
}

IMessageListener is defined in Spring.Messaging.NMS. Build and run the console.

Start jconsole

The JDK comes with a utility called jconsole. You’ll find it in the bin folder. So, launch a command prompt and cd to the bin folder of the JDK. Then type:

jconsole

This will launch the Java Monitoring & Management Console. To connect to the running instance of ActiveMQ, select Remote Process as shown below:

jconsole_activemq

Enter the following in the Remote Process text box: service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi It’s easier to work out what to enter here than you might think. If you go back to the command prompt in which you launched ActiveMQ and look towards the top of the output, you’ll find a line that reads:

INFO  ManagementContext - JMX consoles can connect to service:jmx:ri:///jndi/rmi://localhost:1099/jmxrmi

Click Connect. Select the MBeans tab. Navigate to org.apache.activemq->localhost->Queue->test.queue->Operations->sendTextMessage as shown below:

Sending a text message from jconsole.

In the text box next to the sendTextMessage button, enter some text. I entered (somewhat unimaginatively) “Hello”. Now, click sendTextMessage. In the .NET console window for the listener, you should see the text you entered. So what just happened? jconsole put a message on the queue using JMS and our console application read it using NMS. Why not send yourself a couple more messages?

The Sender

To complete our foray into messaging with ActiveMQ, let’s create an application that can send messages. Create another Console Application. I called mine SenderConsole. You may have started to notice a pattern in my naming conventions. Add the same references you added to the listener console. Here’s the code for the sender console:

using System;
using System.Collections.Generic;
using System.Text;

using ActiveMQ;
using Spring.Messaging.Nms;

namespace SenderConsole
{
    class Program
    {
        private const string URI = "tcp://localhost:61616";
        private const string DESTINATION = "test.queue";

        static void Main(string[] args)
        {
            ConnectionFactory connectionFactory = new ConnectionFactory(URI);
            NmsTemplate template = new NmsTemplate(connectionFactory);
            template.ConvertAndSend(DESTINATION, "Hello from the sender.");
        }
    }
}

Run the sender console and you should find that the message “Hello from the sender.” has appeared in the console window of the listener.

Conclusion

Sending and receiving messages using ActiveMQ is enabled by NMS and Spring.Messaging.NMS. We’ve seen how to create a simple set up using .NET that can be extended for real-world needs. JMS is no longer the preserve of Java developers.

48 Responses

Subscribe to comments with RSS.

  1. erik scheirer said, on June 6, 2007 at 1:55 am

    Excellent! In this age of blogs galore, where nothing is checked, I was thrilled to see that this example actually runs! I cannot find the words to express my appreciation.

    Cheers!

    e

  2. drain said, on June 15, 2007 at 10:02 pm

    Super job! Everything worked perfect! Thanks!

  3. evil drain said, on June 19, 2007 at 4:24 pm

    The example is accurate.

    #1. Console.WriteLine(”Press any key to exit.”);

    The above line will not continue by pressing “any key”. The client needs to supply a carriage return.

    #2. Console.WriteLine(”Press any key to exit.”);

    After supplying a carriage return to the above prompt, the client hangs. The client is not coded properly as to avoid the hanging, the following step must take place to properly release the client from the queue/topic…

    listenerContainer.Shutdown();
    connection.Stop();
    connection.Dispose();

    In order to accomplish this, the client must be coded in a different manner where listener container and connection are not local variables.

  4. remark said, on June 19, 2007 at 9:42 pm

    Thanks drain. I’ve updated the code sample accordingly. SimpleMessageListenerContainer implements IDisposable, so I’ve wrapped it in a using block (I used Reflector to ensure the Dispose method calls Shutdown.)

  5. Tao said, on August 6, 2007 at 7:22 pm

    I tried as written above, the code was built successfully, but a run time error indicates that it can not load the type “ConnectionFactory”, I tried other types in ActiveMQ, none of them can be initialized. I double checked the reference, the ActiveMQ.dll was there, could you give me clue?

  6. derek said, on August 9, 2007 at 12:26 am

    This was very useful, thanks for the example!

  7. Suma said, on August 16, 2007 at 5:51 pm

    Hi,

    I tried running the samples. The Listener works perfect with jconsole sending messages. When I tried to execute the Sender, I get a java.io.IOException: The volume for a file has been externally altered so that the opened file is no longer valid” ACtiveMQ.BrokerException at the template.ConvertAndSend() line.

    Any thoughts?
    Thanks, Suma.

  8. remark said, on August 20, 2007 at 9:46 pm

    Suma,
    I’ve not seen this problem. Might be worth logging the issue on the ActiveMq User Forum.

  9. dash said, on November 14, 2007 at 12:53 am

    Great article! I followed the mentioned steps and everything worked perfectly as expected.

    Quick question: is there a way (or an article) to get similar notifications on a web (.aspx) page rather than console window?

    Thanks in advance.

  10. remark said, on November 22, 2007 at 8:54 am

    Dash,

    Thanks for the feedback. I haven’t tried to use a web page instead of a console, but there’s a couple of things you could try. The first is the ActiveMQ WebConsole. It works with ActiveMQ 5 and above. The other thing to try would be Ajax – ActiveMQ exposes a RESTful interface that you could call from client-side JavaScript. What you want to avoid is having page-related code server side that is waiting around for messages. Of course, having server-side code listening for messages that the pages interact with differently (e.g. Ajax again) would work. Hope this helps.

  11. Herman said, on February 27, 2008 at 3:29 pm

    LS,

    I tried compiling the example on both VS2005 and VS2008 but keep getting the errormessage : The type or namespace name ‘Listener’ could not be found (are you missing a using directive or an assembly reference?) C:\Documents and Settings\Herman\Local Settings\Application Data\Temporary Projects\ListenerConsole\Program.cs 27 61 ListenerConsole
    I am using activemq 5.0 and the SpringNMS version mentioned in the article.
    I am not experienced in c# programming. Did anyone experience the same or knows a solution for this ?

    Herman

  12. remark said, on February 27, 2008 at 10:51 pm

    To compile the Program class, you need to have the Listener class in the same namespace. So, check to see that you have added a Listener class to the ListenerConsole project.

  13. Herman said, on February 27, 2008 at 11:17 pm

    Thanks a lot. Working now as expected.
    Great article.

    Herman

  14. isaac said, on March 28, 2008 at 3:16 am

    Great example!
    The sender program does not exit properly after sending the message.

  15. remark said, on March 28, 2008 at 11:33 am

    isaac,

    Thanks for the feedback. Do you have any more information about how it’s not exitting properly?

  16. Mark said, on April 2, 2008 at 4:15 am

    This is a fantastic example! Very useful.

    I have the same problem as Isaac. The sender program doesn’t terminate after the message is sent. Cntl C is required to stop the Sender program.

  17. Gerald said, on April 11, 2008 at 7:55 am

    I don’t know how long ago this snippet-example was posted by you, but THANKS regardless. I have one question though. After compiling, ran, and performed some testing with .NET and Java environment altogether (ie sending-receiving from different platform), I noticed that in your example, ActiveMQ-NMS doesn’t provide “Topic” as a destination (in comparison with ActiveMQ-JMS). It only provides “Queue”. Is this true?

  18. remark said, on April 11, 2008 at 10:04 am

    Gerald,

    ActiveMQ topics can be used via NMS. I posted an article about publish-subscribe using NMS and ActiveMQ that shows topics being used. Click here to read the full article.

  19. [...] ActiveMQ via .NET Messaging Overview [...]

  20. Kpatel said, on June 3, 2008 at 12:05 am

    This Documentation is Excellent. gives me good knowledge.

    I tried and everything is working even i m sending and receiving message. but when i tried to connect through jconsole i want be able to se that MBeans settings with this “service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi” ad connect. could u please tell this portion… would be help me else all is fine. the way explain is strong very good written ideas also.

    thanks,
    help the developer like me

  21. Marty said, on June 13, 2008 at 1:06 am

    I implemented the examle, and am having one issue I would like to get some feedback on.

    Here is how to reproduce

    Start ActiveMQ
    Start the C# Listener
    Shutdown ActiveMQ
    Startup ActiveMQ

    The C# listner does not re-attach the connection. Any suggestions on how to approach this?

  22. Ben said, on July 9, 2008 at 2:03 am

    KPatel, I am using ActiveMQ 5.1.0 on Windows XP (JDK 1.6.0r05). This version of ActiveMQ doesn’t appear to launch a management interface as per the article (or perhaps it’s because I don’t have J2EE installed). In any case, when I run ActiveMQ you can see that there is no message like “INFO ManagementContext – JMX consoles, etc.”. However if the ActiveMQ instance is running locally, you can connect to it as a Local Process using JCconsole. You should see a line saying “C:\Program Files\activemq…/bin/run.jar” or equivalent in the Local Process panel in the JConsole ‘New connection’ window. Simply select this and click ‘Connect’ instead.

  23. Alex said, on July 17, 2008 at 1:34 am

    Marty, I ran into the same issue as you.
    The feature you are looking for is called failover but unfortunately it’s not supported in the .net version of the API and an enhancement request has been logged against it for quite some time now.
    https://issues.apache.org/activemq/browse/AMQNET-26
    The solution I will attempt to write will basically use retries with exponential backoff to reconnect on network and broker errors. This is the same approach that JMS is using.

  24. Danish Ahmed said, on July 24, 2008 at 2:01 pm

    Hi Ben
    In ActiveMQ 5.1.0 management is turned off by default in configuration file confi/activemq.xml in managementContext node. Turn it on by setting attribute “createConnector=true” and resstart activemq. Hope u will get the required message.

    Regards
    Danish

  25. David Kepes said, on August 5, 2008 at 1:20 am

    Hi, I am having a problem running this example, the listener is not receiving all the messages, am I missing some kind of configuration?
    thanks for your help

  26. Jan Bludau said, on August 5, 2008 at 3:13 pm

    Hello everybody,

    this is a very nice introduction in the activeMQ.
    i’ve tested it with the Apache 5.1.0 version and it works :-)

    Thanks in Advance for this information :-)

    best regards from germany
    Jan Bludau

  27. mark said, on August 25, 2008 at 8:02 pm

    Thanks for the code.

    Any samples of how to set the expiration (TTL) of a message? NMSExpiration doesn’t seem to work for me.

    I’ve tried:
    this.producer.Send(textMessage, false, 1, new TimeSpan(10000000));

    and

    TimeSpan mytime = new TimeSpan(0,0,10);
    textMessage.NMSExpiration= mytime;
    this.producer.Send(textMessage);

  28. feno said, on September 16, 2008 at 11:13 pm

    Thanks for the code. However I tried compiling the example on and VS2008 but keep getting the errormessage :
    ‘ListenerConsole.Listener’ does not implement interface member ‘Spring.Messaging.Listener.IMessageListener.OnMessage(System.Messaging.Message)’ C:\Users\feno\Documents\Visual Studio 2008\Projects\NMS\NMS\Listener.cs

    I am using activemq 5.1.0 and the SpringNMS 1.2.0 M1.
    I am not experienced in C# programming.
    Did anyone experience the same or knows a solution for this ?

  29. feno said, on September 17, 2008 at 8:56 am

    in found the solution in the Spring.Net reference :
    for the class listerner, just add :
    using Spring.Messaging.Nms.Core;
    using Apache.NMS;

    that all !

    for info, in main program, i have
    using Apache.NMS;
    using Apache.NMS.ActiveMQ;
    using Spring.Messaging.Nms;
    using Spring.Messaging.Nms.Listener;

  30. Pradeep Nair said, on September 25, 2008 at 11:34 am

    Excellent

  31. JuliusR said, on October 13, 2008 at 10:38 am

    Thank for the code.

    I have already test the code and its working. But my problem is I want to list all the queues in active MQ.

  32. Prasad said, on November 14, 2008 at 2:52 pm

    hi,

    this code is pretty useful. But i want to have the ListenerConsole
    as a windows service with auto startup. Can you please help me, how to do it?

    Thanks in advance

  33. NZorn said, on November 24, 2008 at 12:37 pm

    Hi there,

    I have listeners which are spawn by a windows service (consumers are defined in xml config and spawn by spring framework).

    if I want to update the windows service with new exe I have to stop the service, update, and then start the service again.

    To do so I need the existing listeners to finish processing the messages that are already in process but not listen to any new messages (like draining in IIS).

    Is it possible to turn of listeners? If so, how can it be done?

    Many thanks

    N

  34. James Strachan said, on December 16, 2008 at 11:45 am

    Great stuff!

    I’ve added a link to the Articles section of the ActiveMQ website…
    http://cwiki.apache.org/ACTIVEMQ/articles.html

  35. Gleb said, on January 5, 2009 at 3:11 pm

    Thank you, very useful article. Having trouble with listener, it doesn’t receive messages.
    A first chance exception of type ‘Spring.Messaging.Nms.Listener.MessageRejectedWhileStoppingException’ occurred in Spring.Messaging.Nms.dll
    A first chance exception of type ‘System.IO.EndOfStreamException’ occurred in mscorlib.dll

    Still looking for solution.

  36. Gleb said, on January 5, 2009 at 4:08 pm

    sorry, my fault. Moved occasionally Console.Read from using block.
    Thank you very much one more time.

  37. [...] are some examples using the Spring framework (same as [...]

  38. Rod said, on February 21, 2009 at 7:16 pm

    Hello,
    The sender does not work for me! I receive the following error.
    Do I have to create a config file ? I’m new to Spring.
    Thank you very much for your help.

    at Apache.NMS.ActiveMQ.Transport.ResponseCorrelator.Request(Command command, TimeSpan timeout)
    at Apache.NMS.ActiveMQ.Connection.SyncRequest(Command command, TimeSpan requestTimeout)
    at Apache.NMS.ActiveMQ.Connection.SyncRequest(Command command)
    at Apache.NMS.ActiveMQ.Connection.CheckConnected()
    at Apache.NMS.ActiveMQ.Connection.SyncRequest(Command command, TimeSpan requestTimeout)
    at Apache.NMS.ActiveMQ.Connection.CreateSession(AcknowledgementMode sessionAcknowledgementMode)
    at Spring.Messaging.Nms.Support.NmsAccessor.CreateSession(IConnection con)
    at Spring.Messaging.Nms.Core.NmsTemplate.Execute(ISessionCallback action, Boolean startConnection)
    at Spring.Messaging.Nms.Core.NmsTemplate.Send(String destinationName, IMessageCreator messageCreator)
    at Spring.Messaging.Nms.Core.NmsTemplate.ConvertAndSend(String destinationName, Object message)

  39. Rod said, on February 21, 2009 at 7:18 pm

    Sorry, this was the stacktrace, the excpetion message is :

    System.ArgumentOutOfRangeException: Index and length must refer to a location within the string.
    Parameter name: length
    at System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy)
    at System.String.Substring(Int32 startIndex, Int32 length)
    at Apache.NMS.ActiveMQ.OpenWire.StringPackageSplitter.StringPackageSplitterEnumerator.System.Collections.IEnumerator.get_Current()
    at Apache.NMS.ActiveMQ.OpenWire.OpenWireBinaryWriter.Write(String text)
    at Apache.NMS.ActiveMQ.OpenWire.BaseDataStreamMarshaller.LooseMarshalString(String value, BinaryWriter dataOut)
    at Apache.NMS.ActiveMQ.OpenWire.V2.ConnectionIdMarshaller.LooseMarshal(OpenWireFormat wireFormat, Object o, BinaryWriter dataOut)
    at Apache.NMS.ActiveMQ.OpenWire.OpenWireFormat.LooseMarshalNestedObject(DataStructure o, BinaryWriter dataOut)
    at Apache.NMS.ActiveMQ.OpenWire.BaseDataStreamMarshaller.LooseMarshalCachedObject(OpenWireFormat wireFormat, DataStructure o, BinaryWriter dataOut)
    at Apache.NMS.ActiveMQ.OpenWire.V2.ConnectionInfoMarshaller.LooseMarshal(OpenWireFormat wireFormat, Object o, BinaryWriter dataOut)
    at Apache.NMS.ActiveMQ.OpenWire.OpenWireFormat.Marshal(Object o, BinaryWriter ds)
    at Apache.NMS.ActiveMQ.Transport.Tcp.TcpTransport.Oneway(Command command) : Transport connection error: Index and length must refer to a location within the string.
    Parameter name: length

  40. Karthikeyan Manickam. said, on February 24, 2009 at 9:47 am

    Hi,

    If anybody would know how to get the messages from the topic. By using the above example I easily got the queue mesages. But i donno how to retrieve the messages from the TOPIC, If anybody can guide me or give me some samples for the same. I would really apperciate and thankful to them.

    Thanks and Cheers…
    Karthikeyan Manickam.

  41. Anthavio Lenz said, on March 3, 2009 at 2:14 pm

    To Rod: Got same problem after getting newer 1.1.0.0 snapshot from svn, but fortunately I still have working older version. NMS 1.1 seems to be bit unstable through the time. Like ActiveMQ…

  42. David said, on March 27, 2009 at 8:19 am

    With .Net and ActiveMQ, is there any possible way to send/receive messages via port with security protocol? I am looking the way for a long time. Thank you.

  43. Sam said, on April 26, 2009 at 6:17 am

    A while back I had built (on a XP box) a C# client using this example as a starter. When I ported that program to a Vista PC recently, it stopped working. The program was connecting via a forwarded port (127.0.0.1:61616) to a MQ running on a remote host.

    Has anyone run into a similar issue on vista? I do suspect his to be an issue with vista and have tried changing security settings etc. but no luck so far.

    Thanks.

  44. Sam said, on April 26, 2009 at 6:19 am

    Should have mentioned, the error is: “unable to connect…machine actively refused connection….{IPv6 of localhost}:61616

  45. viral said, on April 28, 2009 at 7:49 pm

    I have a stomp html page connected to ws://localhost:8001/activemq and subscribed to /topic/stock

    right now when i run stock.start.bat, i can see messages in the stomp html page.

    what i want to do is, i want to generate messages from c# win form application and want to see those messages in stomp html page.

    i tried using “The Sender” part discussed above using “template.ConvertAndSend(DESTINATION, “Hello from the sender.”);” by setting destination as topic.stock but could not get message appear in html stomp page.

    can any one has an idea how to do this ?

    thanks,
    viral

  46. viral said, on April 28, 2009 at 7:50 pm

    I have a stomp html page connected to ws://localhost:8001/activemq and subscribed to /topic/stock

    right now when i run stock.start.bat, i can see messages in the stomp html page.

    what i want to do is, i want to generate messages from c# win form application and want to see those messages in stomp html page.

    i tried using “The Sender” part discussed above using “template.ConvertAndSend(DESTINATION, “Hello from the sender.”);” by setting destination as topic.stock but could not get message appear in html stomp page.

    can any one has an idea how to do this ?

    thanks,
    viral

  47. robin said, on June 17, 2009 at 3:42 am

    Thank you, very useful article.
    But I am Having trouble with listener, it doesn’t receive messages.

    I checked send queue is ok..

    Can anyone help for me?

    Thanks in advance..

    • robin said, on June 18, 2009 at 2:58 am

      Sorry.. I solved it.. I didn’t change any program source… Thanks


Leave a Reply