Time for action – sending messages to all connected browsers
Carry out the following steps:
- Open the
game.js
file in the server folder for the server-side logic. - 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); });
- That is it for the server side. Move on to the
client
folder and open theindex.html
file. - 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>
- 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 theonmessage
event handler...