Time for action – sending a message to the server through WebSockets

  1. First, code the server logic.
  2. Open servergame.js. Add the following function to the file that handles user messages:
    Room.prototype.handleOnUserMessage = function(user) {
      var room = this;
      user.socket.on("message", function(message){
        console.log("Receive message from " + user.id + ": " + message);
      });
    };
  3. Add the following code inside the Room.prototype.addUser method that calls our newly created function:
    this.handleOnUserMessage(user);
  4. Now, move on to the client folder.
  5. Open the index.html file and add the following markup in the body section. This provides inputs for the user to type and send messages to the server:
    <input type="text" id="chat-input" autocomplete="off"> <input type="button" ...

Get HTML5 Game Development by Example : Beginner's Guide - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.