3. A Simple Messaging Program in .NET C#

The following .NET C# program shows how to create a connection, create a session, send messages using a sender, and receive messages using a receiver.

Example 2.3. "Hello world!" in .NET C#

using System;
using Org.Apache.Qpid.Messaging;  (1)

namespace Org.Apache.Qpid.Messaging {
    class Program {
        static void Main(string[] args) {
            String broker = args.Length > 0 ? args[0] : "localhost:5672";
            String address = args.Length > 1 ? args[1] : "amq.topic";

            Connection connection = null;
            try {
                connection = new Connection(broker);
                connection.Open();   (2)
                Session session = connection.CreateSession();   (3)

                Receiver receiver = session.CreateReceiver(address);   (4)
                Sender sender = session.CreateSender(address);   (5)

                sender.Send(new Message("Hello world!"));

                Message message = new Message();
                message = receiver.Fetch(DurationConstants.SECOND * 1);   (6)
                Console.WriteLine("{0}", message.GetContent());
                session.Acknowledge();   (7)

                connection.Close();   (8)
            } catch (Exception e) {
                Console.WriteLine("Exception {0}.", e);
                if (null != connection)
                    connection.Close();
            }
        }
    }
}

(1)

Selects the Qpid Messaging namespace. A project reference to the Org.Apache.Qpid.Messaging dll defines the Qpid Messaging namespace objects and methods.

(2)

Establishes the connection with the messaging broker.

(3)

Creates a session object, which maintains the state of all interactions with the messaging broker, and manages senders and receivers.

(4)

Creates a receiver that reads from the given address.

(5)

Creates a sender that sends to the given address.

(6)

Reads the next message. The duration is optional, if omitted, will wait indefinitely for the next message.

(7)

Acknowledges messages that have been read. To guarantee delivery, a message remains on the messaging broker until it is acknowledged by a client. session.acknowledge() acknowledges all unacknowledged messages for the given session—this allows acknowledgements to be batched, which is more efficient than acknowledging messages individually.

(8)

Closes the connection, all sessions managed by the connection, and all senders and receivers managed by each session.