J2EE Messaging
879
The client uses the session object to create a publisher on the topic it just established. The
createPublisher(Topic topic) method creates a publisher on a given topic. The topic parameter
specifies which topic the publisher will publish to:
// Create a publisher on the topic
topicPublisher = topicSession.createPublisher(topic);
The client uses the session object to create a message. The Publisher only uses a single message object
throughout the example that has its contents reset every time the user inputs a new message. The
message is of type javax.jms.TextMessage and it carries a String. There are five different message
types, which we will look at later in the "Message Body" section of this chapter:
// Create a message object
message = topicSession.createTextMessage();
The last line of the constructor starts the connection so we can publish. The client must start the
connection before it can send or receive messages:
topicConnection.start();
}
The Publisher's publish() method sets the message text, then publishes the message:
public void publish(String msg) throws JMSException
{
The setText(String text) method sets the contents of the message. The text parameter contains
the text with which the message is set:
// Set the text of the message
message.setText(msg);
// Publish the message
topicPublisher.publish(message);
}
/**
* Closes JMS connection objects.
*/
public void close() throws JMSException
{
topicPublisher.close();
topicSession.close();
topicConnection.close();
}
/**
* Writes messages to the topic until the user enters 'q' or 'Q'.
*/
public static void main(String[] args) throws Exception
{
// Create a publisher.
Publisher publisher = new Publisher();