Chapter 23
890
As in the Pub/Sub model, a PTP client may set a message listener to receive messages asynchronously,
like the Receiver in this example, or may use the receive() and receiveNoWait() methods to
receive messages synchronously:
public void onMessage(Message msg)
{
try {
String text;
if(msg instanceof TextMessage)
{
// If the message is a text message, extract the text
text = ((TextMessage)msg).getText();
}
else
{
// If the message is not a text message, convert the message to a string
text = msg.toString();
}
System.out.println("Message Received: "+ text);
// If the message is a single q then quit
if(text.equalsIgnoreCase("q"))
{
Again, we use the synchronized variable to control access to the quit variable because quit is used in
both this thread and the main thread:
synchronized(this)
{
// Set quit to true to let main() know we are done
quit = true;
// Notify main thread to quit
this.notifyAll();
}
}
}
catch(JMSException jmse)
{
jmse.printStackTrace();
}
}
/**
* Closes JMS connection objects.
*/
public void close() throws JMSException
{
queueReceiver.close();
queueSession.close();
queueConnection.close();
}