Java Reference
In-Depth Information
<chat-message>
<type>ChatMessage</type>
<user>admin</user><message>![CDATA[I've forgotten my password]]></message>
<chat-message>
The JSON message has only 79 characters versus 126 characters for the XML message.
That is a 59% increase in the size of message going from JSON to XML and in the amount
of data that must be transmitted and loaded into memory. Of course, the trade-off is that
XML is self-documenting, and when combined with XML Schema, it can be validated.
This isn't possible with JSON, although there are efforts to address this shortcoming.
In JavaScript the message in listing 14.4 can be converted into a JavaScript object and the
properties easily accessed. The code in the following listing is an implementation of the
onMessage callback.
Listing 14.5. Converting a JSON message into a JavaScript object
In this listing you receive a JSON message from a WebSocket callback . You then eval-
uate the data payload of the message, thus converting it into a JavaScript object. Once the
message is converted into a JavaScript object, you can access the properties with ease.
Later in this chapter, you'll see how to marshal JSON into Java objects. Support for pro-
cessing JSON was added in Java EE 7 via JSR-353.
You now have a fundamental understanding of WebSockets. Let's briefly contrast We-
bSockets with existing pre-HTML5 technologies. None of them are a complete or fully
standardized solution.
14.2.2. WebSockets versus AJAX
AJAX (Asynchronous JavaScript and XML) is an older technique for exchanging between
the client and server. Like WebSockets, the client initiates AJAX invocations. But unlike
WebSockets, the invocations are synchronous—the client sends a message to the server and
Search WWH ::




Custom Search