Menu Search

2.3. A Simple Messaging Program in .NET C#

The following .NET C# [1] 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)

Permits use of Org.Apache.Qpid.Messaging types and methods without explicit namespace qualification. Any .NET project must have a project reference to the assembly file Org.Apache.Qpid.Messaging.dll in order to obtain the definitions of the .NET Binding for Qpid Messaging namespace.

(2)

Establishes the connection with the messaging broker.

(3)

Creates a session object on which messages will be sent and received.

(4)

Creates a receiver that receives messages from the given address.

(5)

Creates a sender that sends to the given address.

(6)

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

(7)

Acknowledges receipt of all fetched messages on the session. This informs the broker that the messages were transfered and processed by the client successfully.

(8)

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




[1] The .NET binding for the Qpid C++ Messaging API applies to all .NET Framework managed code languages. C# was chosen for illustration purposes only.