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 messages to all connected browsers


Carry out the following steps:

  1. Open the game.js file in the server folder for the server-side logic.

  2. Add the following highlighted code to the message event listener handler:

    user.socket.on("message", function(message){
      console.log("Receive message from " + user.id + ": " + message); 
      // send to all users in room.
      var msg = "User " + user.id + " said: " + message;
      room.sendAll(msg);
    });
  3. That is it for the server side. Move on to the client folder and open the index.html file.

  4. We want to display the chat messages in the chat history area. To do this, add the following code to the HTML file:

    <ul id="chat-history"></ul>
  5. Next, we need the client-side JavaScript to handle the received message from the server. We used it to print it out into the console panel, replace the console.log code with the following highlighted code in the onmessage event handler:

    socket.onmessage = function(e) {
      $("#chat-history").append("<li...