Java Reference
In-Depth Information
asynchronous messages, the first step is to register some form of call back
address with the server. Then, whenever the server decides that a message should
be sent, it is sent to this call back location using an agreed upon protocol. Differ-
ent frameworks may use different message formats and protocols and varying
transport, but conceptually they work the same.
Typically, when the client receives an asynchronous message, the receiver frame-
work is running in its own thread and dispatches messages either from that
thread or via a thread from a thread pool. If you recall, JavaFX runs in its own
main thread and all updates to JavaFX objects must occur on that main thread.
This requires that the message be pushed onto the main JavaFX thread before
any JavaFX objects are modified. The main objective of this code recipe is to
show how to receive an asynchronous message from the server, and then move it
into the JavaFX main thread for processing.
To illustrate this, we will use an example based on the Java Messaging Service
(JMS) API. In this example, the server process publishes to a JMS Topic; the
JavaFX client subscribes to the JMS Topic and receives the messages. This is the
classical Pub/Sub paradigm.
For our simple example, the server, written in Java, periodically updates the
time. This kind of service is useful if the client application needs to synchronize
its notion of time with the server platform. Every second, the server sends a
JSON message to the JMS topic named “clock”. The message includes the milli-
seconds obtained from the Java call, System.currentTimeMillis() . The fol-
lowing is an example of this JSON message.
{ "clock": "1232822581540" }
The client receives this message and displays the time represented by the clock
millisecond value in a JavaFX Text object as shown in Figure 12.2. This is
updated roughly every second.
Figure 12.2
JavaFX Call Back - Clock
To implement this in the JavaFX client, first create a Java class, called Sub-
scriber . This class connects to the JMS broker, subscribes to the “clock” topic,
then starts listening for messages. The Subscriber class implements the
Search WWH ::




Custom Search