I'm creating a node.js webpage of a tabletop card game and I originally built the application on the backend while being able to only handle one game at a time (as I only tested one at a time). Now that I'm incorporating the front end, and need the ability to process multiple games at a time, I'm struggling with how to receive a user's name and id code and either create or join a specific game while still remembering on client side who the player themselves is:
Earlier algorithm:
--Have global variable player and update to the user inputed name with post req (via express).
--send user gameView.html file
--from there (client side) const socket = io.connect(), socket.emit('newPlayer', socket.id)
--create a player object linking the socket id and global variable player
--reset the global player variable to ""
--continue waiting for the rest of the players
Obviously this is very sloppy practice and was only being used for the development of the backend. Now that I need to handle multiple users and games my algorithm (ideally) would work as such:
--User posts their name and an id code via the prePlayView.html file
--send user the gameView.html file as well as the inputted name and id (this is the part i'm not sure how to implement, as socket id changes after new file is sent so there's no way to track on server side)
--On client side, const socket = io.connect(), socket.emit('newPlayer', name, id);
--if id is blank then create game object with unique id and store in dictionary of games with key id and add player
Any ideas? am i fundamentally missing something? I'm fairly new to node.js.
Here's my current implementation for reference:
var app = express();
app.set('port', 5000);
// called when a player enters the game
app.post("/userView.html", function(req, res) {
var body = "";
req.on('data', function(char) {
body += char;
});
req.on('end', function () {
var playerName = body.substr(body.indexOf("=") + 1, body.indexOf("&") - 4);
var id = body.substr(body.indexOf("&") + 4, body.length);
body = "";
var options = {
headers: {
'id': id,
'names': playerName
}
}
res.sendFile(path.join(__dirname, 'userView.html'), options);
});