Java Reference
In-Depth Information
5.
Starts the connection, causing message delivery to begin:
connection.start();
6.
Receives the messages sent to the destination until the end-of-message-stream con-
trol message is received:
while (true) {
Message m = consumer.receive(1);
if (m != null) {
if (m instanceof TextMessage) {
message = (TextMessage) m;
System.out.println("Reading message: " + mes-
sage.getText());
} else {
break;
}
}
}
Because the control message is not a
TextMessage
, the receiving client termin-
ates the
while
loop and stops receiving messages after the control message ar-
rives.
7.
Closes the connection in a
finally
block, automatically closing the session and
MessageConsumer
.
The
receive
method can be used in several ways to perform a synchronous receive. If
you specify no arguments or an argument of
0
, the method blocks indefinitely until a mes-
sage arrives:
Message m = consumer.receive();
Message m = consumer.receive(0);
For a simple client, this may not matter. But if you do not want your application to con-
sume system resources unnecessarily, use a timed synchronous receive. Do one of the fol-
lowing:
• Call the
receive
method with a timeout argument greater than
0
:
Message m = consumer.receive(1); // 1 millisecond
• Call the
receiveNoWait
method, which receives a message only if one is avail-
able: