Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Practice exercises CHAPTER 10 427



  1. Add a statement to map a request for the root to the index.html file (to be created in
    Exercise 2) as follows.
    app.get('/', function (req, res) {
    res.sendfile(__dirname + '/public/index.html');
    });


The index.html file is the main chat page.


  1. Add code to redirect the user to the default.html page if the URL does not include a
    file name, as follows.
    app.get('/', function (request, response) {
    response.redirect('default.html');
    });

  2. Add a statement to create a usernames variable and initialize it as an empty object, as
    follows.
    var usernames = {};

  3. Add code to subscribe to the socket.io events as follows.
    io.sockets.on('connection', function (socket) {
    socket.on('sendchat', function (data) {
    io.sockets.emit('updatechat', socket.username, data);
    });


socket.on('adduser', function(username){
socket.username = username;
usernames[username] = username;
socket.emit('updatechat', 'SERVER', 'you have connected');
socket.broadcast.emit('updatechat', 'SERVER'
, username + ' has connected');
io.sockets.emit('updateusers', usernames);
});

socket.on('disconnect', function(){
delete usernames[socket.username];
io.sockets.emit('updateusers', usernames);
socket.broadcast.emit('updatechat', 'SERVER'
, socket.username + ' has disconnected');
});
});

The first line of this code subscribes to the connection event and executes an anony-
mous function. The anonymous function code accepts a socket parameter, which is
the object that represents the newly created user connection. Inside the anonymous
function, subscriptions are created to the sendchat, adduser, and disconnect events.
The sendchat and adduser events are developer-defined.
The sendchat event is triggered when a message is received from a chat client. This
code uses the io.sockets object to broadcast the message to all chat clients.
Free download pdf