Book Image

HTML5 Game Development by Example: Beginner's Guide

By : Seng Hin Mak
Book Image

HTML5 Game Development by Example: Beginner's Guide

By: Seng Hin Mak

Overview of this book

Table of Contents (18 chapters)
HTML5 Game Development by Example Beginner's Guide Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
9
Building a Physics Car Game with Box2D and Canvas
Index

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" value="Send" id="send">
  6. Then, add the following code to the html5games.websocket.js JavaScript file. This sends the message to the server when the user clicks on the send button or presses the Enter key:

    $("#send").click...