The Java EE 5 Tutorial

Writing the Client Programs for the Asynchronous Receive Example

The sending program is producer/src/java/, the same program used in the example in A Simple Example of Synchronous Message Receives.

An asynchronous consumer normally runs indefinitely. This one runs until the user types the letter q or Q to stop the program.

    The receiving program, asynchconsumer/src/java/, performs the following steps:

  1. Injects resources for a connection factory, queue, and topic.

  2. Assigns either the queue or topic to a destination object, based on the specified destination type.

  3. Creates a Connection and a Session.

  4. Creates a MessageConsumer.

  5. Creates an instance of the TextListener class and registers it as the message listener for the MessageConsumer:

    listener = new TextListener();consumer.setMessageListener(listener);
  6. Starts the connection, causing message delivery to begin.

  7. Listens for the messages published to the destination, stopping when the user types the character q or Q:

    System.out.println("To end program, type Q or q, " + "then <return>");
    inputStreamReader = new InputStreamReader(;
    while (!((answer == ’q’) || (answer == ’Q’))) { 
        try { 
            answer = (char); 
        } catch (IOException e) { 
            System.out.println("I/O exception: " + e.toString()); 
  8. Closes the connection, which automatically closes the session and MessageConsumer.

    The message listener, asynchconsumer/src/java/, follows these steps:

  1. When a message arrives, the onMessage method is called automatically.

  2. The onMessage method converts the incoming message to a TextMessage and displays its content. If the message is not a text message, it reports this fact:

    public void onMessage(Message message) { 
        TextMessage msg = null; 
        try { 
            if (message instanceof TextMessage) { 
                msg = (TextMessage) message; 
                 System.out.println("Reading message: " + msg.getText()); 
            } else { 
                 System.out.println("Message is not a " + "TextMessage"); 
        } catch (JMSException e) { 
            System.out.println("JMSException in onMessage(): " + e.toString()); 
        } catch (Throwable t) { 
            System.out.println("Exception in onMessage():" + t.getMessage()); 

You will use the connection factory and destinations you created in Creating JMS Administered Objects for the Synchronous Receive Example.