■ Implement bidirectional communication with the WebSocket API
■
■ Make webpages dynamic with jQuery and AJAX
■
■ Wire up an event with jQuery
■
■ Implement a callback with an anonymous function
■
■ Use the this pointer
Implementing bidirectional communication with the WebSocket API
The WebSocket API provides bidirectional communication support to your web applications.
WebSocket has greatly simplified the way data can be sent and received. Traditional methods, such as long polling, have existed for a long time and are widely used all over the web today.
However, traditional techniques use the heavier HTTP mechanisms, which make the applica-tion inherently less efficient. The use of the WebSocket API allows the connecapplica-tion directly to a server over a socket. This is a much lighter weight connection and is fully bidirectional; both binary and text-based data can be sent and received.
NOTE ACCEPTING SOCKET CONNECTIONS
The full implementation of a WebSocket API requires that a webserver have a proper server-side implementation that can accept socket connections. Technologies such as Node.js work well for this purpose. Implementation of such technologies is beyond the scope of this book, and these code samples assume such an implementation exists.
The use of the WebSocket API is ideal for real-time applications such as messenger/chat applications, server-based games, and more advanced scenarios, such as WebRTC (Web
ptg14200515 Real-Time Communication) video conferencing. The data transmitted over WebSockets can
be text based or binary. The code in Listing 2-1 demonstrates the WebSocket API.
LISTING 2-1 Implementation of the WebSocket API
<script type="text/javascript">
window.onload = function (){
var wsConnection;
var chatBox = document.getElementById("chatWindow");
var disconnectButton = document.getElementById("Disconnect");
var connectButton = document.getElementById("Connect");
var sendButton = document.getElementById("Send");
var msgToSend = document.getElementById("msgSendText");
disconnectButton.onclick = function () {
ptg14200515
<div align="center">
<div>
<input type="text" id="msgSendText" style="width: 300px"/>
</div>
<div>
<button id="Disconnect">Disconnect</button>
<button id="Connect">Connect</button>
<button id="Send">Send</button>
</div>
</div>
</body>
The primary object that you will work with is the WebSocket object, which connects to the socket when its constructor is invoked. In Listing 2.1, a variable is declared but not instanti-ated until a user invokes the connect button. When the user clicks the button, the WebSocket is instantiated with the appropriate connection information:
wsConnection= new WebSocket('ws://studygroup.70480.com', ['soap', 'xmpp']);
The WebSocket constructor accepts two parameters:
■
■ The URL of the server-side socket to connect to, which is always prefixed with ws or wss for secure WebSocket connections
■
■ An optional list of subprotocols
When the WebSocket constructor is called, the WebSocket API establishes a connection to the server. One of two things can happen at this stage. The WebSocket will successfully connect to the server or the connection will fail, resulting in an error. Both cases should be
ptg14200515 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.
ptg14200515
TABLE 2-9 Possible values of the WebSocket readyState
Value Description
OPEN The connection is open.
CONNECTING The connection is in the process of connecting and not ready for use yet. This is the default value.
CLOSING The connection is in the process of being closed.
CLOSED The connection is closed.
After confirming that the connection is in the appropriate state for sending a message, the send method is called with the text that the user entered into the chat application. Also, so that each user can see that his/her message is indeed part of the chat, the message is added to the chat window.
When other users of the chat application send messages into the system, the server calls the event handler specified in onmessage. The onmessage event receives a message parame-ter with the data property that contains the message. This message is extracted and displayed in the chat window for users to see.
When finished with a chat session, a user should be able to exit cleanly. This is accom-plished by calling the close method of the WebSocket object. The close method can be called with no parameters. It also allows the use of two optional parameters. A numerical code and a reason can be provided but isn’t mandatory. In this example, the connection is closed with no parameters. When a connection is closed, the onclose event handler is raised:
disconnectButton.onclick = function () { wsConnection.close();
}
wsConnection.onclose = function () {
//write the connection has been closed.
NewLine();
chatBox.value = chatBox.value + "System: Connection has been closed.";
}
When the user clicks the close button, the close method is called. Then, the subsequent call to the onclose event handler is implemented so that a message can be provided to the user that the connection has indeed been closed.