Client.java is the client application. It starts by creating a connection, a session, and a destination queue, to which requests are sent. It also creates an exception listener for the connection so that any message errors can be caught.
// Load JNDI properties
Properties properties=new Properties();
properties.load(this.getClass().getResourceAsStream("requestResponse.properties"));
//Create the initial context
Context ctx=new InitialContext(properties);
// Lookup the connection factory
ConnectionFactory conFac = (ConnectionFactory) ctx.lookup("qpidConnectionfactory");
// create the connection
QueueConnection connection = (QueueConnection) conFac.createConnection();
connection.setExceptionListener(new ExceptionListener()
{
public void onException(JMSException jmse)
{
// The connection may have broken invoke reconnect code if available.
System.err.println(CLASS + ": The sample received an exception through the ExceptionListener");
System.exit(0);
}
});
The session for this example is a Java JMS QueueSession.
QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
Client uses a Java JMS QueueRequestor, a class that directly supports the kind of service request that is at the heart of this example. We will use the request queue as our destination.
Queue destination = (Queue) ctx.lookup("requestQueue");
QueueRequestor requestor = new QueueRequestor(session, destination);
Now we start the connection so that we can receive responses to our requests.
connection.start();
We will use a function called sendReceive() to send a request and receive the response. Here is the code that calls sendReceive(), which is described later.
TextMessage request;
String[] messages = {"Twas brillig, and the slithy toves",
"Did gire and gymble in the wabe.",
"All mimsy were the borogroves,",
"And the mome raths outgrabe."};
for (String message : messages)
{
request = session.createTextMessage(message);
sendReceive(request, requestor);
}
After calling sendReceive(), we close down as in the other examples.
connection.close(); getInitialContext().close();
The sendReceive() function simply sends a request, receives the response, and prints it:
private void sendReceive(TextMessage request, QueueRequestor requestor) throws JMSException
{
Message response;
response=requestor.request(request);
System.out.println(CLASS + ": \tRequest Content= " + request.getText());
String text;
if (response instanceof TextMessage)
{
text=((TextMessage) response).getText();
}
else
{
byte[] body=new byte[(int) ((BytesMessage) response).getBodyLength()];
((BytesMessage) response).readBytes(body);
text=new String(body);
}
System.out.println(CLASS + ": \tResponse Content= " + text);
}