HTML and CSS Reference
In-Depth Information
handled so that the proper feedback is provided to the application user. The WebSocket API
provides an event for each, called onopen and onerror, as shown earlier in Listing 2-1:
// event handler for when the WebSocket connection is established
wsConnection.onopen = function () {
chatBox.textContent = chatBox.textContent +
"System: Connection has been established";
}
//event handler for when the WebSocket encounters an error
wsConnection.onerror = function (err) {
//write an error to the screen
NewLine();
chatBox.value = chatBox.value + "System: Error Occurred.";
}
In this example, both event handlers are providing feedback in the chat window to let
users know of either a successful connection or the occurrence of an error. The error event
could happen at any time, not just when establishing the initial connection.
When a successful connection is established, you can send and receive messages over the
socket. To send messages, the WebSocket API provides the Send function. To receive mes-
sages, the WebSocket API provides the onmessage event handler. These two methods show
the functions and events that handle the bidirectional communication:
wsConnection.onmessage = function (msg) {
//write message
NewLine();
chatBox.value = chatBox.value + "Them: " + msg.data;
}
sendButton.onclick = function () {
//check the state of the connection
if (wsConnection.readyState == WebSocket.OPEN) {
//send message to server.
wsConnection.send(msgToSend.value);
}
else
return;
//show message in chat window.
NewLine();
chatBox.value = chatBox.value + "You: " + msgToSend.value;
//clear message text box
msgToSend.value = '';
}
The first method is an event handler for the send button provided in the HTML. Users
click this button to send messages to other users of the chat application. The WebSocket API
provides a mechanism to check the current status of the connection. To prevent an error, the
readyState property is evaluated to ensure that it's now open. readyState provides four pos-
sible values, as described in Table 2-9.
 
Search WWH ::




Custom Search