Java Reference
In-Depth Information
Once the connection has been upgraded, both the client and server can immediately begin
transmitting messages back and forth. The content of the messages is application-depend-
ent. The content can be binary data, XML, text, JSON, and so on. Currently, most applica-
tions use JSON because it's compact and easy to work with in JavaScript. XML, although
self-documenting, is verbose and consumes significant overhead in both transmission and
processing. The overhead can translate into performance problems, especially with mobile
devices.
Sending data from JavaScript to the server involves invoking the send method on the We-
bSocket object. There are several different methods depending on the data type you want
to transmit:
void send(DOMString data);
void send(Blob data);
void send(ArrayBuffer data);
void send(ArrayBufferView data);
In this chapter we'll focus primarily on sending text data, such as JSON, but you can also
send binary and array data. The text method transmits the text as Unicode—text that isn't
Unicode is converted to Unicode. The structure of the message can be anything—you're
free to format your messages however you see fit. Most of the time, though, you'll probably
utilize JSON. JSON is compact and works well with JavaScript. In addition, with Java EE
7, you can marshal JSON directly into Java objects using the Java API for JSON process-
ing (JSR-353). Let's look at a simple example of JSON plus WebSockets in the following
listing.
Listing 14.3. Sending a JSON using WebSockets
Here a JavaScript Object, msg , is created to which several properties are added: type ,
text , and date .
 
Search WWH ::




Custom Search