Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

432 CHAPTER 10 WebSocket communications



  1. 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.
    ///

  2. 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.

  3. Subscribe to the connect, updatechat, and updateusers events of the socket.

  4. 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.


  1. 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?"));
    }

  2. Add the processMessage function.
    This function is called when the chat service sends a message. The username and data
    are passed to this function.

  3. Use jQuery to create a jQuery object with the response and insert the message after
    the conversation
    element.
    The processMessage function should look like the following.
    function processMessage(username, data) {
    $('' + username + ': ' + data + '
    ')
    .insertAfter($('#conversation'));
    }

Free download pdf