J2EE Messaging
889
Receiving a Message
The following short example creates a JMS client that is a receiver on MyJMSQueue. The code is online
in the Receiver.java file:
package ptp;
iimport common.*;
import javax.jms.*;
import javax.naming.*;
public class Receiver implements MessageListener
{
private QueueConnection queueConnection = null;
private QueueSession queueSession = null;
private Queue queue = null;
private QueueReceiver queueReceiver = null;
public boolean quit = false;
public Receiver() throws NamingException, JMSException
{
// Obtain an initial context - JMS Vendor Specific
InitialContext ctx = WeblogicJMSDetails.getInitialContext();
// Create a connection
QueueConnectionFactory queueConFactory = (QueueConnectionFactory)
ctx.lookup(WeblogicJMSDetails.JMS_CONNECTION_FACTORY);
queueConnection = queueConFactory.createQueueConnection();
// Create a session
queueSession =
queueConnection.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);
// Create a receiver on the queue
queue = (Queue)ctx.lookup(WeblogicJMSDetails.QUEUE_NAME);
The Receiver creates a queue receiver to receive messages on MyJMSQueue. The
createReceiver(Queue queue) method creates a Receiver for a queue. The queue parameter
specifies the queue that the client wishes to listen on (MyJMSQueue, in this case):
queueReceiver = queueSession.createReceiver(queue);
The Receiver's constructor sets up a message listener to listen for messages sent to its queue:
// Set ourselves as the listener for the messages
queueReceiver.setMessageListener(this);
// Start connection
queueConnection.start();
}
The onMessage() method is just like the one from the Subscriber example. It is called by the broker
when a message arrives at MyJMSQueue. Its body prints out the messages that it receives to the screen.