J2EE Messaging
887
Sending a Message
The following short example is a JMS client that sends console input to MyJMSQueue until a q or Q is
entered. The code is on the Web site in the Sender.java file:
package ptp;
import common.*;
import java.io.*;
import javax.jms.*;
import javax.naming.*;
public class Sender
{
private QueueConnection queueConnection = null;
private QueueSession queueSession = null;
private Queue queue = null;
private QueueSender queueSender = null;
private TextMessage message;
public Sender() throws NamingException, JMSException
{
// Obtain an initial context - JMS Vendor Specific
InitialContext ctx = WeblogicJMSDetails.getInitialContext();
// Look up the connection factory
QueueConnectionFactory queueConFactory = (QueueConnectionFactory)
ctx.lookup(WeblogicJMSDetails.JMS_CONNECTION_FACTORY);
// Create a connection
queueConnection = queueConFactory.createQueueConnection();
// Create a session
queueSession =
queueConnection.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);
After the constructor sets up the connection and the session it looks up the MyJMSQueue and then
creates a queue sender. The createSender(Queue queue) creates a sender on the specified queue
(in this case, MyJMSQueue):
// Look up the queue
queue = (Queue)ctx.lookup(WeblogicJMSDetails.QUEUE_NAME);
// Create a sender on the queue
queueSender = queueSession.createSender(queue);
// Create a message object
message = queueSession.createTextMessage();
// Start up the connection so we can send messages.
queueConnection.start();
}