I've recently been getting in to node.js in order to make an online game (for education). Through reading various tutorials I've come up with the simple code shown below. With the code I have I'm capable of client-server communication, which is mostly all I need in order to make the game. There's only one problem, only the client can initiate conversation whereas the server can only respond. In addition to this, I also need to at any moment in time send the current game state from the server to the client. For example, in a 2 player game, when a player sends a command that alters the game state, that new game state needs to be forwarded to BOTH players.
Is there a simple way in node.js to do this? I know that you can't simply send a message to the client since the client cannot be expected to have a port opened for the server to use, but maybe there's a way for the client to leave behind a connection for the server to use? I'm the kind of guy that learns by example, thus some simple working code would be appreciated.
Btw, I'm hosting the game on firebase, in case that's relevant.
index.js:
const functions = require('firebase-functions');
const express = require('express');
const app = express();
app.post('/game', (request, response) => {
request.body.randomNumber = Math.random();
console.log(request.body);
response.json(request.body);
});
exports.app = functions.https.onRequest(app);
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type="text" id="commandbox" onkeypress="send(this)">
<br>
<div id="display"></div>
<script>
const send = (ele) => {
if (event.key === 'Enter') {
console.log(ele.value);
const json = {
name: "John",
gender: "male",
age: 25,
message: ele.value
};
postToGame(json);
}
};
</script>
<script>
const postToGame = (json) => {
const xhr = new XMLHttpRequest();
xhr.open("POST", '/game', true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onload = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("display").innerHTML = xhr.responseText;
}
};
xhr.send(JSON.stringify(json));
}
</script>
</body>
</html>