Java Reference
In-Depth Information
Sending binary data is useful in situations such as a file upload where you want to stream
a large file to a server. The send method can transmit data only if the WebSocket connec-
tion has been opened; otherwise an error will be thrown. The error will be delivered the
onerror callback, which we'll cover next.
In addition to sending data to the server, WebSockets can also receive data asynchronously.
To accomplish this, WebSockets provide a number of callback hooks:
webSocket.onopen = function(evt) { /* Open Callback */};
webSocket.onclose = function(evt) { /* Close callback */};
webSocket.onmessage = function(evt) { /* Async message */ };
webSocket.onerror = function(evt) { /* Error callback */ };
These hooks cover the complete lifecycle of a WebSocket. The first callback, onopen ,
is invoked once the WebSocket connection to the server has successfully opened and can
send and receive data. The onclose method is invoked when the WebSocket connec-
tion has been closed. Either the client or the server could have terminated the connec-
tion. The onerror callback is invoked when there's an error with the connection, such
as when you attempt to transmit data on a closed connection. The onmessage callback
is invoked when a message arrives from the server. The server can send a message back at
any point—it doesn't have to be in response to a request from the client, like in the case
of AJAX. The contents of the message can be an ArrayBuffer , Blob , or String . To
retrieve the contents of the message, access the data property on the event.
Most of the time the data will be transmitted using JSON. JSON is much simpler and less
verbose than XML. It's easier to parse and takes up less bandwidth; both are important
attributes when dealing with mobile devices. The JSON format has two structures: name/
value pairs and an ordered list of values. In the case of Action-Bazaar, the next listing
shows a simple chat message in JSON format.
Listing 14.4. Example ActionBazaar chat message
"type": "ChatMessage",
"user": "admin",
"message", "I've forgotten my password"
The chat message in this listing is simple. It's an array of three properties or values. This
message is much more compact than the equivalent XML message:
Search WWH ::

Custom Search