432 CHAPTER 10 WebSocket communications
- Open the default.js file. To get IntelliSense, from the Solution Explorer window, drag
the jquery-1.8.3.js file and drop it at the top of the default.js file to add a reference to
the jQuery library as follows.
/// - Declare a socket variable. Subscribe to the ready event of the document. In this code,
use the io object to connect to the chat service and assign the result to the socket
variable. - Subscribe to the connect, updatechat, and updateusers events of the socket.
- Finally, subscribe to the click event of the datasend button and the keypress event of
the data text box, as follows.
var socket;
$(document).ready(function () {
socket = io.connect('http://localhost:8080');
socket.on('connect', addUser);
socket.on('updatechat', processMessage);
socket.on('updateusers', updateUserList);
$('#datasend').click(sendMessage);
$('#data').keypress(processEnterPress);
});
This code is subscribing to the events, which execute functions that are not yet created.
You add these functions next.
- Add the addUser function, which calls the emit method on the socket to call the
adduser method on the chat server.
The result of the pop-up prompt for the username is also passed. The addUser func-
tion should look like the following.
function addUser() {
socket.emit('adduser', prompt("What's your name?"));
} - Add the processMessage function.
This function is called when the chat service sends a message. The username and data
are passed to this function. - Use jQuery to create a jQuery object with the response and insert the message after
the conversationelement.
The processMessage function should look like the following.
function processMessage(username, data) {
$('' + username + ': ' + data + '
')
.insertAfter($('#conversation'));
}