Adding server-side libraries for javascript - javascript

I am currently coding my offline game into an online game by use of node.js and socket.io
In my game, I use vectors from a library called p5.js to store position of player, collision related movement, etc.
However, the server side (a txt file called "server.js") does not have p5.js like the client, so I can't send information about the player's with vectors.
Here is my question: How could I make the server.js file have access to my p5.js library?
Note: Simply sending x and y values, and then using them to make a vector would be a difficult solution, as I would no longer be able to send a single array holding all the information of all players. Also, enemies, food, trail positions, and much more also depend on vectors. Coverting all of these would be difficult to code.

What you want to do is simple, but it won't feel simple until you fully understand all the parts involved, and for that I'm afraid it's going to take you at least a few months given your current level.
How could I make the server.js file have access to my p5.js library?
Is your p5.js a browser-only library, or you can import it as a module in your server? If it's the second option, all you have to do for your server to access it is:
const p5 = require('p5.js');
Keep in mind that:
Server should handle the position, movement, and actions of players so they can't cheat.
The client should be just a visual display of the information coming from the server, plus sending the player key inputs to the server.
So unless you want to make client side prediction and entity interpolation, which I doubt because you are starting out, keep it simple. No need to share libraries between client and server yet.

Related

How to implement server-side multiplayer for a simple JS game?

Thank you, this is my first post so please correct me on any etiquette. I am a beginner programmer and I want to make a game in JavaScript for one of my classes. Specifically, my Latin class for an "anything" project. My goal is to make somewhat of a Roman-themed version of Among Us. I already have basic movement, and an Apache server running my game. The only thing that I need help with here is making it multiplayer.
The way I want to do this is to have an array on the server where each row is a player, and their username, password, coordinates, and various states (connected, dead, role, etc.) is stored in each column. Only the username, coordinates, and some of the states need to be made available to each client. This is to be copied into an array for each client, who will then take this information and display it.
A client takes control of their character by entering their index and password, at which point a 1D array on the client-side will be created that stores their coordinates, which can be changed by the player using their controls, and sent to the server to be stored in the main array.
I've honestly tried to research this, and I have learned a little bit about databases like MySQL, and server-side languages like PHP and node.js. The problem with these is that, as far as I know, they run once at loading and cannot be manipulated further.
I don't care about anything like separate lobbies at this point, my class is of only 30.
Does anyone know of any good libraries or tutorials for this? Or is there a better direction to go entirely? I hope to make this mobile-compatible.
If needed, I can provide the URL to my website and the code so far.
You want to figure out if you're going to do it in 3D or 2D, pick your language, and implement what you said in said language.
The main thing I think you're missing is the data transport, which can be provided to you with a TCP websocket library like socket.io or socks, which will facilitate an instant, constant data flow between server and client.
The other thing you're missing is a graphics library, which you can do more research on after you figure out whether or not you're doing 2D or 3D.

Inner workings of browser based real-time MMO games

So, suppose there was a game which consisted of a website, and a client that you can launch from said website. I've looked a bit and a relatable example would be Habbo Hotel.
What I'm asking is, what are all the different parts that would make such a game work: for the website part, I'd imagine a server, a database, and some HTML, CSS and PhP coding would be required, but how would the client side operate?
More specifically, how would the client-to-server (and vice versa) real-time communications happen?
Suppose the client be coded in C, how would the integration of C into a (I suppose PhP-framed) browser window be executed?
Note that the client is never downloaded on the user's PC, so where would it reside?
I'm sorry if these are a lot of questions, if the answers were to be too tedious to compose, feel free to just leave some documentation or tutorials (which I've looked for but haven't really been able to find), I'll happily read them on my own. Thanks in advance.
On one side your question is too broad but on the other side I can give you some pointers of how to do this in a modern way:
don't have a client, just a page in a browser
use HTML5 canvas, you may also want to look into SPA (single page application)
connect via websocket, there are HTML5 javascript implementations and PHP or node.js for the server-side
best is, use node.js on the server, PHP would be way too cumbersome
via websocket, send and receive JSON objects
host node.js on its native platform (Linux)
you may want to look into phaser as an HTML5 client-side canvas rendering framework, but it lacks many functionality and is mainly oriented towards twitch-based action games, which don't work well with this architecture because of lag
this will lead you to one conclusion: javascript is at the center of this system. you'll encounter several roadblocks, such as:
security on websockets with SSL for login
avoid SSL for real-time data (above 1 Hz)
UI on the client inside the canvas is not easy to implement, you'll have to re-invent the wheel or find a UI library for that
expect lag, the network code will take some 20%-30% overhead in respect to native C/C# code using TCP/IP or UDP (Lidgren?) and protobuf (Lidgren+protobuf) is what high-frequency AAA titles use (MMORPG or FPS alike)
From the questions you asked I sense a great lack of understanding and knowledge about the field. I guess you'll have to study some 6-12+ months beforehand. This is what I recommend, because if you start right away you'll make a lot of errors and waste your time. If above are any names you don't know about, search them and study them well. And don't start to code, there is a very steep learning curve ahead of you!
EDIT: more about server-side
If you want to implement an action-based interactive game (like an FPS or 2D shooter) I have to tell you this.
You may want to look into Unity 3D, using directly TCP/IP connections and binary messages (no HTTP, no websocket, instead protobuf).
C# (client-side) and node.js (server-side) are a good combination. For horizontal scaling you may want to look into cloud computing, docker, provisioning and a lot of server security.
But this is hostile terrain, it leads you into DevOps territory, which is way off game development. More like an architect's job. Imagine that 3-tier system (client + server + database) has a bottleneck on the server.
You want to spawn more nodes to handle more clients. This is what EVERY lobby-based game does (LoL, Overwatch, WoT, WoW instances, and so on) and what you do for partitioned maps (e.G. the "maps" in LOTRO, RIFT, many more MMORPGS). Also, to mirror (which means multiple instances of the same map to accomodate an overpopulated crowd).
To have this kind of horizontal scaling your servers must go online/offline on their own without you clicking around on command and control (e.G. puppet and similar software).
While this is the ultimate approach, it also has the most steep learning curve, especially because of security (advert DDOS, flooding, slow-loris, fake clients, and the list goes on). A new node must be "provisioned" on the fly (e.G. cloud-config) before it attaches to the cluster and goes online, so there's a whole new world of pain and learning.
The center-piece of such an elastic cloud-based server system is SSO (single sign-on).

Porting OpenGL Programs from C to WebGL and Javascript

I'm trying to port a very complex 3D modeling program(written in C) to webGL. The program has it's own physics engine written from scratch, and I would like to use the transform data which is output by the physics engine as matrices to transform objects rendered in a webPage.
The program is so massive that I would like to keep the physics engine in C as is, but take the graphics part into the browser.
My crazy idea is to have the physics engine running constantly on the server, and then stream the transformation matrices to the client and apply the transformations to pre-rendered WebGL objects.
Is this possible to do?
Clarification: The program is a viewer, so all of the physics backend is isolated from user input. The user will, however, be able to manipulate camera angles on the client side.
Update: I've decided on implementing the following solution, let me know if any of this is wrong: I will host the C program as a daemon using node.js, and pump data using websockets to the front end - which is pixi.js(for 2D elements) and babylon.js(or three.js)(for 3D elements). The data will be comprised of JSON objects(quaternions or sine/cosine matricies) that will be handled on the front end in javascript and applied once per second(fps doesn't matter in my situation, so it's okay)
Push and pop matrix are auxiliary (not a core part of the rendering pipeline) so you can replicate them with a custom stack.
About the whole crazy idea:
In case of interactive physics, latency can be a problem and you will need some sort of position extrapolation on the client side. Worst case is if you have multiply clients. Imagine that one client caused some physics event then it will send data to the server and server will send it to the another client. So you will have effectively double latency and at the end it will be really hard to resolve inconsistency when you have 3 states (or even more if you have more clients) one unique state at each client and one actual state at server. The bigger the latency - the higher inconsistency. And physics is really sensitive to this kind of inconsistency, because it tends to snowball. So your clients likely to see some weird popping in and out of existence, teleportations, falling through solid objects.
Implemented this successfully by doing the following:
Within my C code I used the hiredis library to publish a JSON formatted string to redis, hosted on an ec2 machine with nginx. Next I used primus(a node_module) to set up a subscriber websocket from redis to a node.js app server. Node then serves the data(whenever there's a publish) to the client, where I parsed out the JSON and used the object to draw my scene.
This solution is really quick and easy, and is a very effective means of pushing large amounts of data(in the form of a JSON object) through to many clients. It also allows for setting up multiple channels within C(for different datasets), at which point you can pick and choose which channels you want to listen to on the client side(or listen to all of them at once!). I'm away from my computer with the code, but I can post more detailed instructions/code examples on how to do this at a later time.

Client or server-side HTML5 canvas rendering for a node.js whiteboard application?

I was thinking a little whiteboard web app would be a nice way to improve my node.js and JavaScript skills. I've seen a few on the web, which makes sense as it seems ideal for this kind of stack.
Just taking a moment to think, however, I was wondering about the roles of both client and server in this kind of web application. Stumbling upon node-canvas, I became even more confused. What, specifically, should the client and server be responsible for?
If the server is capable of rendering to a canvas, should it accept and validate input from the clients and then broadcast it to all other connected users via socket.io? This way, the server keeps a master-canvas element of sorts. Once a new user connects, the server just has to push out its canvas that client - bringing it up to pace with whatever has been drawn.
Any guidance on implementation - specific or philosophical - is appreciated.
Thanks!
I wrote http://draw.2x.io, which uses node-canvas (previously node-cairo, which I wrote myself) along with socket.io.
The way I've designed my application, the client essentially does all the stroke generation from user input. These are in turn processed by a canvas abstraction, which supports a subset of operations and parameters which I've defined myself. If this layer accepts whatever input the painting modules produce, they are also shipped, via socket.io, to the server.
On the server I've got the same kind of canvas layer wrapping node-canvas. This will thus replicate the input from the user in memory there, eventually making it possible to send a state image to new clients. Following this, the strokes will -- pending parameter / context validation by the server application -- be published to other connected clients, which will repeat the same procedure as above.
A company I work for implemented a whiteboard app with node.js (but did not use node-canvas) and socket.io. Unfortunately, I cannot give you code or even a website since it has not been released.
Your implementation seems very similar. Clients connect to our server and update the server whenever the whiteboard is drawn to (JSON data w/(x,y) coordinates) through socket.io. The server then updates the rest of the clients and keeps a copy of all the (x,y) coordinates so that new clients who join can see what has already been drawn.
Good luck with your app. I've been programming with node.js a lot lately and boy do I love it.
here's a multiuser whiteboard tutorial written in javascript/html5, all source available:
http://www.unionplatform.com/?page_id=2762
it's not node on the server-side, but the client-side code should still be useful if you want to adapt it to a node backend.

What good ways are there to prevent cheating in JavaScript multiplayer games?

Imagine a space shooter with a scrolling level. What methods are there for preventing a malicious player from modifying the game to their benefit? Things he could do that are hard to limit server-side is auto-aiming, peeking outside the visible area, speed hacking and other things.
What ways are there of preventing this? Assume that the server is any language and that the clients are connected via WebSocket.
Always assume that the code is 100% hackable. Think of ways to prevent a client completely rewritten (for the purposes of cheating) from cheating. These can be things such as methods for writing a secure game protocol, server-side detection, etc.
The server is king. Clients are hackable.
What you want to do is two things with your websocket.
Send game actions to the server and receive game state from the server.
You render the game state. and you send input to the server.
auto aiming - this one is hard to solve. You have to go for realism. If a user hits 10 headshots in 10ms then you kick him. Write a clever cheat detection algorithm.
peeking outside the visibile area - solved by only sending the visible area to each client
speeding hacking - solved by handling input correctly. You receive an event that user a moved forward and you control how fast he goes.
You can NOT solve these problems by minifying code. Code on the client is ONLY there to handle input and display output. ALL logic has to be done on the server.
You simply need to write server side validation . The only thing is that a game input is significantly harder to validate then form input due to complexity. It's the exact same thing you would do to make forms secure.
You need to be really careful with your "input is valid" detection though. You do not want to kick/ban highly skilled players from your game. It's very hard to hit the balance of too lax on bot detection and too strict on bot detection. The whole realm of bot detection is very hard overall. For example Quake had an auto aim detection that kicked legitedly skilled players back in the day.
As for stopping a bots from connecting to your websocket directly set up a seperate HTTP or HTTPS verification channel on your multiplayer game for added security. Use multiple Http/https/ws channels to validate a client as being "official", acting as some form of handshake. This will make connecting to the ws directly harder.
Example:
Think of a simple multiplayer game. A 2D room based racing game. Upto n users go on a flat 2D platformer map and race to get from A to B.
Let's say for arguments sake that you have a foolsafe system where there's a complex authetication going over a HTTPS channel so that users can not access your websocket channel directly and are forced to go through the browser. You might have a chrome extension that deals with the authentication and you force users to use that. This reduces the problem domain.
Your server is going to send all the visual data that the client needs to render the screen. You can not obscure this data away. No matter what you try a silled hacker can take your code and slow it down in the debugger editing it as he goes along until all he's left with is a primitive wrapper around your websocket. He let's you run the entire authentication but there is nothing you can do to stop him from stripping out any JavaScript you write from stopping him doing that. All you can achieve with that is limit the amount of hackers skilled enough of accessing your websocket.
So the hacker now has your websocket in a chrome sandbox. He sees the input. Of course your race course is dynamically and uniquely generated. If you had a set amount of them then the hacker could pre engineer the optimum race route. The data you send to visualise this map can be rendered faster then human interaction with your game and the optimum moves to win your racing game can be calculated and send to your server.
If you were to try and ban players who reacted too fast to your map data and call them bots then the hacker adjusts this and adds a delay. If you try and ban players who play too perfectly then the hacker adjusts this and plays less then perfect using random numbers. If you place traps in your map that only algorithmic bots fall into then they can be avoided by learning about them, through trial and error or a machine learning algorithm. There is nothing you can do to be absolutely secure.
You have only ONE option to absolutely avoid hackers. That is to build your own browser which cannot be hacked. Build the security mechanisms into the browser. Do not allow users to edit javascript at runtime in realtime.
At the server-side, there are 2 options:
1) Full server-side game
Each client sends their "actions" to the server. The server executes them and sends relevant data back. e.g. a ship wants to move north, the server calculates its new position and sends it back. The server also sends a list of visible ships (solving maphacks), etcetera.
2) Full client-side game
Each client still sends their actions to the server. But to reduce workload on the server, the server doesn't execute the actions but forwards them to all other clients. The clients then resolve all actions simultaneously. As a result, each client should end up with an identical game. Periodically, each client sends their absolute data (ship positions, etc.) to the server and the server checks if all client data is identical. Otherwise, the games are out of sync and someone must be hacking.
Disadvantage of the second method is that some hacks remain undetected: A maphack for example. A cheater could inject code so he sees everything, but still only sends the data he should normally be able to see to the server.
--
At the client-side, there is 1 option:
A javascript component that scans the game code to see if anything has been modified (e.g. code modified to render objects that aren't visible but send different validation data to the server).
Obviously, a hacker could easily disable this component. To fix that, you could force the client to periodically reload the component from the server (The server can check if the script file was requested by the user periodically). This introduces a new problem: the hacker simply periodically requests the component via AJAX but prevents it from running. To avoid that: have the component redownload itself, but a slightly modified version of itself.
For example: have the component be located at yoursite/cheatdetect.js?control=5.
The server will generate a slightly modified cheatdetect.js so that in the next iteration, cheatdetect.js?control=22 (for example) must be downloaded. If the control mechanism is sufficiently complicated, the hacker won't be able to predict which control number to request next, and cheatdetect.js must be executed in order to continue the game.
There's nothing you can really do to prevent anyone from modifying your JS or writing a GreaseMonkey script. However you can make it hard for them by minifying your script as well as making your code as cryptic as possible. Maybe even throwing in some fake methods or variables that do nothing but are used to throw an attacker off. But given enough time, none of these methods are completely foolproof, as once your code goes to the client, it is no longer yours.
The only way I can even think of implementing this is by modifying your Javascript to function as a client and then designing a central server mechanism to validate data sent from that client. This is probably a big change to implement and will most likely make your project more complex. However, as was said earlier, if the application runs entirely on the client, the client can pretty much do whatever they want with your script. The only way to secure it to use a trusted machine to handle validation.
They don't have to touch your client-side code -- they could just sniff and implement your Websocket protocol and write a tiny agent that pretends to be a human player.
Update: The problem has a few parts, and I don't have answers off the top of my head, but the various options could be evaluated with these questions in mind:
How far are you willing to go to prevent cheating? If you only care about casual cheating, how many barriers are enough to discourage the casual cheater? The intermediate Javascript programmer? A serious expert? Weighing this against the benefits of cheating, is there anything of real value at stake, like cash and prizes, or just reputation?
How do you get a high confidence that a human is providing inputs to your game? For example, with a good enough computer vision library I could model your game on a separate machine feed inputs to the computer pretending to be the mouse, but this has a high relative cost (not worth my time).
How can you create a chain of trust in your protocol such that knowledge of (2) can be passed to the server, and that your server is relatively confident your client code is sending the messages?
Sure many of the roadblocks you throw up can be side-stepped, but what is the cost to the player and you? See "Attrition warfare".
Some other methods that can be implemented:
Make the target elements difficult for a script to distinguish from other elements. Avoid divs with predictable class and id names if possible. Inject styling using JavaScript instead of using classes. Think like a hacker and make it hard on yourself.
Use decoys that a script will fire on. For instance, if the threat vector is a screen scraping algorithm using pixel colors, throw some common pixel colors in non-target elements. Hits on these non-targets could seem inconsequential to the cheater, but would be detectable. You don't want the cheater to know why you know.
Limit the minimum time between actions to slightly below the best human levels. The best players will hit that plateau, and it won't matter as much who's cheating, and immediately be able to detect anyone scripting faster than that by side-calling method calls.
Random number generators are typically uniform. Human nature is not. Likely a random number generator will have values within a set limit and even distribution. Natural distribution is a Gaussian curve. If you sampled the distribution and it looks like a square wave in the x and y axis, 100% it's a cheater. This will be fairly difficult for the cheater to detect the threshold for the algorithm because it's a derivative of the random, and not the random distribution itself. You're also using aggregate data and not individual plays to detect it, so reverse engineering the algorithm would be extremely difficult without knowing your detection algorithm.
Utilize entropy whenever possible. Avoid predictable game plays. Imagine a racing game on a set collection of race tracks. Each game play could have slightly differing levels of traction, horsepower, and momentum. The script would have to be extremely good to beat it. In a scrolling game, you can alter factors that are instinctual to humans, but difficult for computers, such as wind force, changes in gravity, etc. It would also make it more fun as a side benefit.
Server generated tokens can be used to validate UI elements were used and not calls to the code itself. Validation can be handled in one call at the end of the game comparing events to hashed codes of UI elements. The token should be a hash with a server private key and some value of the UI element.
Decoy the cheater with data they think you're using to detect cheats. Such as calls to a DetectCheat method with dummy calls to a fake backend. It's the old magician's trick. Wave your hand over here, while you slip a card into the deck with the other hand. Let them waste days on end in a maze that has no exit, with lot's of hair pulling.
I'd use a combination of minification and AJAX. If all of the functions and data aren't loaded into the page, it'd be more difficult to cheat.
On the other hand, modding turned out to be a very profitable tool for companies like Id Software. Perhaps allowing the system to be modded might make the game that much more enjoyable to the community at large.
Obfuscate your client exposed code as much as possible. Additionally, use some magic.
You can edit the javascript on the browser and make it work.
Some people suggest that make a call to check with the server. So after making a call to the server, it will be validated in the server. Once validated, it will come to client side and do actions. But I think even this is not foolproof.
For eg.,. for a Basic login action : in angular while making a call to server, the backend validates username & pwd and if validated, it will come back to the client and let the user login using angular.
When I say login using angular, it is going to store things in cookies, like user objects and other things. But still the user can remove the JS code which is making the call to backend, and return TRUE(wherever needed) and insert user object(dummy) to cookies and other objects(whatever needed) and login. It is a very difficult thing to do, but it is doable. In many scenarios, this is not desirable even if it takes hours to edit/hack the code.
This is possible in single page applications, where JS files dont get reloaded for each page. To mitigate the possibility of getting hacked we can use minified codes. And I guess if actions like this is done in backend(like login in Django) it is much safer.
Please correct me if I am wrong.

Categories