Multiplayer game with socket nodeJs, is DB needed? - node.js

I use socket on connection event. new players are created and seen, multiplayer array of objects in console, exists. However, not every event is seen properly (for example, 1. newest connections only see them self, while older see everyone on game. 2. I want also to show all players movements , real time. Dont know how node can handle that). For those issues in brackets, do I need to use Mongo DB or index DB to handle all data real time ?

You will need a database in order for your game to work in a distributed way i.e. so you can scale to more than more server / node process. If you are currently storing all connection/player data in memory, then this won't be accessible by other processes.
With regard to newest connections only see them self, while older see everyone on game I'd need to know more about how/where you store these connections.
For the second point, I want also to show all players movements , real time, I'll need more detail on how you are sending these movements from the client to server, & then broadcasting.

Related

Local DB and syncing of new messages in a chatting app

I am a bit of a bind when it comes to this topic. Here's my situation, I have a discord-like style of the app where you join chat rooms. I now have the issue of how to handle and use a local DB in conjunction with the remote DB. As I'd only load the newest X messages of the current DB and then if the user scrolls get the other X and so on. But where does a local DB come into the picture? For example, I stored in the DB messages from 10 AM - 12 AM, should I get the oldest message from the local DB and skip the timeframe in the remote DB when requesting the data? What if someone deleted/ edited a message? From my current standpoint, it really seems that just having a remote DB is the way to go
Using Nodejs Typescript and MongoDB for the server and the client is a Kotlin multiplatform app and I have access to a SQL DB on the client if necessary.
Also anyhow I approach this, since this is a chatting App and I already have an established Websocket connection, would loading messages and receiving them via the Websocket make sense, or should I make a REST endpoint?
Your localdb is effectively a cache, and you should treat it as such. Now that you have a cache, you have another problem, cache invalidation. Worse, since each client has it's own, you have a distributed cache invalidation issue.
You can probably sidestep a lot of this by making message immutable, and having a REPLACES_ID and an IS_DELETED field which allows an "edit" to really be an add which then from a UI standpoint replaces another existing message.. This will at least give you something fairly computable from a cursor standpoint.
Ideally your ID field is an increasing numeric sequence that allows simple queries like "Give me X messages from this room where ID is greater than [[The last id in your cache]]" If no data is returned, your local DB has all the data, otherwise take data from the query and populate your local database to bring these messages in.
Scrolling is more complicated, but in general can be ignored, nobody scrolls (statistically irrelevant number of people go to page 2). I'd recommend if someone scrolls just wipe the local database past the first page and go back to the remote server for X records BEFORE your current page's first record.

How to store a turn based game state in Node.js

I am developing a turn based mobile game which is a question - answer game. Basicly server will send a question to players (there will be two players in a match) then player 1 answers this question after that, player 2 will be answering too the same question in a limited time order. Players could use jokers such as extend the time or change the question. This is the basic logic of my game. So here is my question:
I will be using Node.js and Socket.io for the server side. You know whether a player losts the connection to the server or simply kills the app starts again during in a match, they should be rejoin the same match and they should see what happened in the game when they were not there. How should i store the game state in my server?
My approach:
There will be a Game class that stores every state of the game and manages the countdowns for turns with setInterval method etc. and when the match starts i will create them and store like this:
activeGames[lobbyId] = new Game(player1, player2, lobbyId)
So for example if a player uses a joker i will catch that request inside the socket.io then retrive my class like this:
var yourGame = activeGames[lobbyId]
yourGame.useBonus(player1, bonusType)
So all the status of the game will be stored inside the class. But with this approach if my server dies or restarts etc. all active matches will be dropped. So that is not a good thing. What do you suggest about this problem? How my server should store the active matches?
Ps: Matches will be lasted for 3 minutes. After that i don't need the match history or something like that. So i am not looking for a persistent database solution.
Generally, you would generate a token (preferrably a cryptographically-secure one) for each client. When a client joins for the first time, generate the game data, and associate that data with the token. Then, send that token to the client. When the client reconnects, it can send that token back to the server, which then re-associates the data with the client.
As for server issues, there are many ways to go about things. What I'd do is create a folder called temp or session or something, then store each game in its own temp file. When the server restarts, it checks the temp folder for game files, loads them, then clears their temp files. You can add handlers for unhandledException and unhandledRejection in NodeJS to save currently active games to their own temp files before the server crashes or shuts down.

Online poker game system with nodejs and socket.io

I am working on a MMO poker game,
Currently the whole poker gameplay system would be handled by socket.io by calculating datas in database, the socket would listen to the client's emit and hit APIs to the database to calculate the cards' strength, pots, player's turn etc..., everything is being stored to the database after every action from player
However, i dont know if this is the good approach, some suggested me that i could calculate whole things in a socket functions, by collecting necessary datas from database, all actions triggred by players would be directly calculated by socket function and after the end of the game, the socket stores the result of the game to the database (there will be less processes in the database)
What are the pros and cons ? Which one will cause bottleneck ?

Storing short term user data on server

I'm implementing a web app in Node.js, a new framework to me. In the app, we pair users together and they share "game data" for the duration of the game. Both users need to be able to query for the current state, push updates to the game state, and recieve updates on the game state. I can do all the event stuff with sockets, but I'm a bit unsure about the proper way to store this data on the server.
I see Node.js has variables that can be accessed from all connections. Would maybe using a global object with unique session IDs as keys and game states and values be viable? Or is there a better way to do this?
You need to use a persistent data store, like a database. If you just use a variable, it could change if the server needs to restart. I recommend MongoDB to get started. It is fast and easy to use when getting started.
MongoDB NodeJS
There are other options like Redis, and many more.

What is the best way to keep track of which users are online in nodejs?

So I am developing (more playing around with) a realtime game in node.js, I am also using Redis and Sockets.io. I have players create a lobby and join it (kind of like a pre-game chat room, where you can talk to players and select game settings) . The client is written in HTML/CSS/JS, Anyway I want to be able to tell when players disconnect from the lobby, to update the number of players joined on the interface (and joined player names).
Two options I have thought about are:
Using redis' key value timeout feature, to remove a particular field if it is not updated in x amount of time. I would then have the host check the existance of this field to check for DC's. I do wonder if this is highly inefficient, as many users potentially will be playing, so will it be bad to have many timeout values in redis and also many other users polling these fields.
I could use the sockets.io on('disconnect', ..) to update the field. However I am not sure if this event will fire if for example a users pc freezes?
Anyway I am open to any other ideas also!
Socket.io have a 'heartbeat' to check connection still alive. Default heartbeat timeout is 15s. You can read more about configuring it in this wiki. If heartbeat fails (user pc freezes) then socket.io will emit 'disconnect' event.
Socket.io should suffice. You can configure it to use heartbeats to ping the socket and check its health. If a user's computer freezes it will, in effect, not be able to respond to these heartbeats, causing it to force a disconnect.
To test this you could set up your Socket.io to use heartbeats, then connect via a browser onn a different computer. While in the browser past into the console an infinite loop. Causing it to simulate a freeze.

Resources