Chapter 23
880
// Publish user's messages until user enters an 'q' or 'Q'.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String msg = null;
do
{
System.out.print("Enter message ('q' or 'Q' quits): ");
msg = in.readLine();
// Publish message if it wasn't empty.
if(msg.trim().length() != 0)
{
The Publisher's publish(Message message) method publishes the message to the topic on which
the publisher was created (MyJMSTopic, in this case). The message parameter specifies the message to
send to the topic. When this program is running, any JMS client listening on MyJMSTopic will receive
the messages the user types in:
publisher.publish(msg);
}
}while(!msg.equalsIgnoreCase("q"));
The Publisher's close() method closes the connection when the program exits:
publisher.close();
}
}
A JMS Subscriber
The following example is a Subscriber for the Publisher example above. The subscriber will continue to
receive messages until it receives a q or Q:
package pubsub;
import common.*;
import javax.jms.*;
import javax.naming.*;
public class Subscriber implements MessageListener
{
// Connection objects
protected TopicConnectionFactory connectionFactory;
protected TopicConnection topicConnection;
protected TopicSession topicSession;
protected TopicSubscriber topicSubscriber;
protected Topic topic;
public boolean quit = false;
/**
* Creates and initializes a Subscriber object.
*/
public Subscriber() throws NamingException, JMSException
{