Java Reference
In-Depth Information
Table 9-1.
JavaScript WebSocket Object Events
Event
Handler Method
Description
open
onOpen
occurs when the WebSocket connection is established
close
onClose
occurs when the WebSocket connection is closed
error
onError
occurs when there is a communication error
message
onMessage
occurs when data is received from the server
After the WebSocket object has been instantiated successfully, a connection to the server will be established,
which will cause the
open
event to occur. To process this event, assign a function to the onOpen handler, and process
events accordingly within that function. Messages can be sent to the server when the open event occurs, and this is
demonstrated within the example.
ws.onopen = function()
{
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
};
Similarly, we can listen for any other events to occur, and then process tasks accordingly when they do. In the
example, when a message is received from the server, it is printed within an
alert
dialog. Also, in the example shown
below when the WebSocket is closed, an
alert
dialog is presented to the user.
The example does not demonstrate all of the possible ways that the WebSocket object in JavaScript can be
utilized. For instance, we could send messages to the server by invoking the
send()
method, and passing the data
that we wish to send as a parameter. The
close()
method can be called on a WebSocket to manually terminate the
existing connection. WebSocket objects also contain the helpful attributes,
readyState
and
bufferedAmount
, that
can be used for obtaining information about a connection. The
readyState
attribute will advise the current state of
the WebSocket connection via a returned number, and the
bufferedAmount
attribute value represents the number of
bytes of UTF-8 text that have been queued using the
send()
method. Table
9-2
displays the different possible values
for the
readyState
attribute, along with a description of each.
Table 9-2.
JavaScript WebSocket readyState Values
Value
Description
0
connection not yet established
1
connection established, and communication is possible
2
connection going through closing handshake
3
connection is closed and cannot be opened
Ready to dig into the code? In the following example, a JavaScript solution is engineered that can be used to send
messages from a client browser to a WebSocket endpoint. Invoke the JavaScript function via an action event that is
bound to an HTML input tag within the view. In the following example, a button contains an
onclick
attribute that
will invoke a JavaScript function named
acmeChatRelay
. The
acmeChatRelay
function is responsible for opening
a session with a WebSocket endpoint so that messages can be sent. The listing below is an excerpt from the
<head>
section of the
/layout/custom_template.xhtml
JSF view, which is located within the
web
directory of the
IntroToEE7 project.