What are possible ways to send Game/Simulation State with javaNIO? - java

i heard this phrase quite often to "send the game state or simulation state " in network game/simulation realm and my question is stem from that and i really need to know how? .
I m working on real time network physics simulation, my question is only that :
*How simulation state can be transfer from server to client*? (the least simulation state are the coordinates X,Y of simulated bodies=))
Possible scenario: taking the example of simple ball simulation, the server is moving the multiple balls and should send coordinates of each ball to client for drawing and updating simulation, and each ball should move according to its received coordinates from the sever.
thanks,
jibbylala
P.S: please don't mention any string based solution i am looking for generic mechanism which can be applicable on different Physics simulation.

In fast paced action games, the state of dynamic objects is sent constantly in structures. By state I mean it is usually position and rotation. Depending on model's architecture, it can be server constantly pushing the states, or sending the change in state when it occurs. More often the first one. When the state is not received in some period of time the game lag occurs. The state can also have parameters such as velocity, acceleration, etc. really depends on game and on how you want to handle game events. Lets say we are writing simple 2D game with flying ships on surface then the state could be a simple class in java like:
class ShipState{
public float x;
public float y;
public float angle;
}
The netcode in game takes care of transporting these structures. Games usually have their own protocol built on top of TCP/IP and UDP to handle everything, since there is lot of different type of information going both ways in real games, not just physical state. If you are serious about your project, you should really look into networking libraries. I strongly doubt there is anything really good, since JAVA is not very popular on this frontier. Single google request brought up this Kryo library which seems pretty good. You could also probably look into netty, which is a very solid general purpose networking library. If I was to write a netcode for game in Java I would just go and dig up open source game networking libraries written in C/C++, such as Enet to get some ideas.
Getting to the bottom of your question, regarding the ball simulation on server, it is as simple as server sending ball coordinates and clients receiving those. If you are not sure how it is done, you probably want to look at these tutorials. And other general Java networking tutorials. Good luck!

Related

Java Networking - Client and server

I'm quite new to Java and have just started Networking so I apologize in advance for any stupid questions. I have a basic game in which a player (or bot) can move around a map until it finds items and exits, but using networking I'd like to be able for the player and the bot to play on the same map simultaneously over a server.
I have 5 classes:
GameRules - Controls the game logic/rules
Map - Contains the map.
Player - Represents a player.
Bot - Plays the game as a bot.
PlayGame - Controls the interaction with the game through CLI.
I'm pretty sure GameRules and Map would be on the server side, and PlayGame would be on the client side, however I'm not sure where Bot and Player class stand? And also, do I merge GameRule and Map into one class, or put a socket in each class?
Thanks a lot.
Most models in a client-server game should reside both on client and server.
The client needs the models to visualize the data they are holding;
The server needs them to modify them according to business logic - the intermediate results are then sent to the clients to have their models updated. The server must do this because that is the reason for its existence: keeping the game's state consistent by being the only node that can alter the game state.
You can always try to keep all models at the clients but imagine what coding horror you'll get yourself into when you want to make a game with N clients. They all have to have a consistent state. It is far more safe to have one node (server) make decisions and then the other nodes must follow instructions.
Please note that in more advanced implementations, like realtime games, the client also implements some prediction behavior to hide the client-server delay, and thus temporarily alters the game state, but the server commands always overrule the client's decisions. You also can code the client in such a way that he is always able to keep playing even when he didn't receive a confirmation yet for the previous "moves" from the server - you have to implement rollback/correction functionality when some moves are denied by the server.
Depending on the complexity of the business logic and synchronization timing needed, it's entirely possible to keep most everything at the client level, and just use the server as a broker for updates. Imagine a 2-player online chess game. The rules are so standard and the timing is simply back-and-forth, so a "server" of this game need only pass each move back and forth from one player to the other. Would be like replacing the mail in your grandfather's chess match with a socket. Each (client) side knows exactly how to process the move and what new moves are valid.

Real-time sockets in java

I'm trying to write multiplayer game for Android with java back-end using sockets, but I don't know how to do some things.
For example, I have to players. First player pushed "UP" button and his avatar moving up. How can I tell about it to all other players?
I can send message, that user with some ID changed his coordinates to new X and Y, but I will need to do that for every millisecond while he moving. Is that right?
Or I can send message that user with some ID pushed UP button and after that new message that user released UP button. Using time difference between this two events and movement speed I can calculate new coordinates of user, but in this case will be problems with latency (time difference calculation will be not enough accurate)
How I can do that?
You can do it in lot of ways and all will have drawbacks like you already found. I guess there is no "best" way to do that.
A common way for games is to have a "game server". The server recieves input from all clients and decides about the resulting state.
Clients could for example just transmit the keypresses and the server tells them about their location and location of other clients that need to be drawn. Clients do the same math locally and display this state while waiting for confirmation from the server. But that's just a prediction.
When it lags you can observe yourself jumping between positions in a lot of games because actual server calculated position and your prediction got out of sync.
The other advantage of server-side state decisions is that clients can't cheat that easily. It's no foolproof way to prevent every cheat. Aim-bots for example simply simulate a perfectly aiming user by moving the mouse for them and that's basically not detectable. Map hacks / wall hacks (anything where you can see things that you would not see) on the other hand can be prevented by simply not telling the client about currently invisible things. Only the server needs to know the full state.
The server approach can also be used without a dedicated game server. Instead, one of the clients will have the role of the server and decide about the game state. That responsibility can in some games even switch between clients if the original host drops out. A smooth handover if that happens is rather tricky though.
If there is no server and all clients are equally responsible you will have to think about schema which defines which client is responsible for validating which action. For example in a shooter, A shoots in a certain direction, and thinks B is still there but B already moved a bit further and now A thinks "B was hit" and B thinks "shot missed" -> Either the one shooting or the one being hit should decide what happens.
A schema with multiple decision making parties might not work for every game and it is a very complicated task. Not just for games but distributed computing in general
Java and Sockets are just tools here. The actual problem is one where you should take pen and paper and think about a schema that works for your scenario.
Regarding coordinates every milisecond: you could also send messages like "I will be at point X,Y at time Z" and other clients interpolate the path of that player so you don't have to transmit every position.

Java Network Game (might use NIO)

As part of a learning experiment, I want to make a network application. I'm still learning about multithreading, and I've made a simple multithreaded "game" that involves drawing sprites on the screen, where the player can move them.
For this new project, I want to make something simple, just for the experience and learning. I want to create a server, where multiple clients can connect to it. The server will contain "game objects", which is just an object containing an x and y position, a string name, an ID to identify it, and velocity (dx and dy).
The "server" application will feature things like a worker thread updating the position of the objects (using their velocity), and it will also send the client the "state" of all game objects, so the clients can draw them for the players to see.
The clients will also send the server data whenever the player presses a button on the keyboard and generates a KeyEvent. The server will read this data and process it by updating the player's game object. For example, if the player presses the left arrow key, the client will send the server data indicating that the left key was pressed, the server will find the game object associated with the client (maybe I will store the objects in a Map like ?)
The problem is how to do this. I've never done any networking of this scale before. The most I've made so far is a buggy 2 player tic tac toe game. Since that is turn based, it is very different the application that I am now trying to make. As research, I read the entire Concurrency lesson on Oracle. I also read this tutorial on NIO. I've never used NIO before but I was recommended by multiple people to use it. I learned a lot about multithreading and concurrency from reading the code and figuring out how it works.
Since the SocketChannels communicate using ByteBuffers, one strategy I thought of is to take a List of GameObjects and serialize it to a byte array. Then create a ByteBuffer with the ByteArray and send it to the client. The client will then get all the GameObjects loaded in the server, and be able to draw all of them based on their type and states. One problem with this is that the byte array could get very large. I tested it with 256 GameObjects, and got a byte array of up to 9KB. If I compress the byte array, the size will be around 96 bytes. Still, I don't know if this is too big to be sent to the client 15 times a second.
Another option that I know of is to send the info byte by byte. For example, the first byte sent could identify what type of game object I am sending (example: cat, car, person), the next two bytes could identify the X position, then the next two the Y position, then the last byte used to identify the state of the object. Using this data, the client can just draw a sprite on the position received.
A big problem with all that I've said is that the client won't be able to interact with any of the objects. The client will just be able to send simple commands to the server, and "view" the game objects' sprites at its position. If the server wanted to tell the a game object to do a specific action, it would be hard to draw it since I will just be drawing static sprites to a screen, instead of interacting with the sprites.
I also am not sure whether or not NIO is the best idea. Most people I've talked to recommend it, but I don't quite understand the practical difference between implementing a non blocking NIO server and a multithreaded regular java.net.* server. My guess is that the non blocking server has better performance than a multithreaded one, and I would run into much less problems with just 1 thread rather than multiple threads per connection.
And finally, I've gotten mixed advice whether or not to use TCP or UDP. I've never used UDP before either. Some strongly suggest TCP, while others strongly suggest UDP.
As you can see, I am pretty unorganized and not sure on what to do. I feel like I have read a lot about networking and concurrency, and I already know enough about Swing to make graphical games. I just don't know how to put it all together.
Perhaps consider using Netty. I have found it extremely useful for rapid application development and fast enough for most server and client applications. You can get faster with a raw implementation of the reactor design pattern with Java NIO, but it will take a lot more work and code that is hard to debug.

Where to begin with sockets in a simple multiplayer JAVA game

I've have recently been exploring my own idea to make a little multiplayer game that a couple of my friends could play just for the fun of it. I know all the basics, a little more to java, i would consider myself an intermediate at java.
Recently I've been learning on how to load sprites, double buffering, key listeners, mouse listeners, etc for making a little side scroller 2d gun game. And I have a good understand of these categories, but now I've come to the part where I need to learn about sockets and such to be able to get this game online.
I've seen a little tutorial on where a server and client were made, and when the client was opened would send a message (string) to the server, for example "Orange" and the server could understand that, and print it out. I can understand the code by looking at it (if asked to reconstruct that from my own knowledge (slash memory) would be unable to, because I don't know sockets).
Now to my main question, how can I start to go about doing something like this, when doing this, how to a registrated the movement,for example, from one client to the server which would then appear on all clients connected and in the game, as well with bullets, collision events, enemies, etc. I cant seem to find any good help out there that really shows you how to do this, by creating a socket, doing all the basic connection stuff (which i dont know) and then updating the game state if i can call it that.
So in all, how can I basically take a game with has a ground, two players (represented by sprites) some enemies (AI) and bullets able to kill the enemies, and the ability for the enemies to fire back and kill the players (Users) and make a server and client out of it? Oh and one more thing, I'd like to have the ability for the player to choose a name as well, and the name lets say would float above the players character in the game... And if is even possible to have a little built in chat function, but i might be getting to advanced on that one.
If someone can just at least point me in the right direction, or explain the basics around all this, then that would be great! Thanks!
-Dan
I apologize if I through a lot out there, I just want to explain what im looking to be able to do
What you will need is a multithreaded server, that listenes for incomming data from the players, and then update accordingly. The client also needs to be threaded and listen for incomming data from the server so it can update other players movement etc. So start by reading up on sockets and threads. You want the server to create one thread for each client that is connected.
Then make a first try by sending messages to a server, which echos back the same messages to the client. This will require that you use threads and sockets and is a good way to start.
You will be using the same tequniqe for your game later (clients send their movement to the server, and the server echos the movement to all the other clients so they can update the changes locally) OR, the clients send movements to the server, the server updates the movements locally. This will require that the clients get x and y cordinates of all the objects stored on the server. This might be better in case of lag (never programmed a game so not sure which approach will be best).
So, you will have infinite loops on both the server and the clients that each iteration gets/sends x and y axis of each object and use that to repaint/handle hits and so on. Which logic lies in which loop will depend on the design you choose.

Best way to implement game playback?

I'm creating a grid based game in Java and I want to implement game recording and playback. I'm not sure how to do this, although I've considered 2 ideas:
Several times every second, I'd record the entire game state. To play it back, I write a renderer to read the states and try to create a visual representation. With this, however, I'd likely have a large save file, and any playback attempts would likely have noticeable lag.
I could also write every key press and mouse click into the save file. This would give me a smaller file, and could play back with less lag. However, the slightest error at the start of the game (For example, shooting 1 millisecond later) would result in a vastly different game state several minutes into the game.
What, then, is the best way to implement game playback?
Edit- I'm not sure exactly how deterministic my game is, so I'm not sure the entire game can be pieced together exactly by recording only keystrokes and mouse clicks.
A good playback mechanism is not something that can be simply added to a game without major difiiculties. The best would be do design the game infrastructure with it in mind. The command pattern can be used to achieve such a game infrastructure.
For example:
public interface Command{
void execute();
}
public class MoveRightCommand implements Command {
private Grid theGrid;
private Player thePlayer;
public MoveRightCommand(Player player, Grid grid){
this.theGrid = grid;
this.thePlayer = player;
}
public void execute(){
player.modifyPosition(0, 1, 0, 0);
}
}
And then the command can be pushed in an execution queue both when the user presses a keyboard button, moves the mouse or without a trigger with the playback mechanism. The command object can have a time-stamp value (relative to the beginning of the playback) for precise playback...
Shawn Hargreaves had a recent post on his blog about how they implemented replay in MotoGP. Goes over several different approaches and their pros and cons.
http://blogs.msdn.com/shawnhar/archive/2009/03/20/motogp-replays.aspx
Assuming that your game is deterministic, it might be sufficient if you recorded the inputs of the users (option 2). However, you would need to make sure that you are recognizing the correct and consistent times for these events, such as when it was recognized by the server. I'm not sure how you handle events in the grid.
My worry is that if you don't have a mechanism that can uniformly reference timed events, there might be a problem with the way your code handles distributed users.
Consider a game like Halo 3 on the XBOX 360 for example - each client records his view of the game, including server-based corrections.
Why not record several times a second and then compress your output, or perhaps do this:
recordInitialState();
...
runs 30 times a second:
recordChangeInState(previousState, currentState);
...
If you only record the change in state with a timestamp(and each change is small, and if there is no change, then record nothing), you should end up with reasonable file sizes.
There is no need to save everything in the scene for every frame. Save changes incrementally and use some good interpolation techniques. I would not really use a command pattern based approach, but rather make checks at a fixed rate for every game object and see if it has changed any attribute. If there is a change that change is recorded in some good encoding and the replay won't even become that big.
How you approach this will depend greatly on the language you are using for your game, but in general terms there are many approaches, depending on if you want to use a lot of storage or want some delay. It would be helpful if you could give some thoughts as to what sacrifices you are willing to make.
But, it would seem the best approach may be to just save the input from the user, as was mentioned, and either store the positions of all the actors/sprites in the game at the same time, which is as simple as just saving direction, velocity and tile x,y, or, if everything can be deterministic then ignore the actors/sprites as you can get their information.
How non-deterministic your game is would also be useful to give a better suggestion.
If there is a great deal of dynamic motion, such as a crash derby, then you may want to save information each frame, as you should be updating the players/actors at a certain framerate.
I would simply say that the best way to record a replay of a game depends entirely on the nature of the game. Being grid based isn't the issue; the issue is how predictable behaviour is following a state change, how often there are new inputs to the system, whether there is random data being injected at any point, etc, You can store an entire chess game just by recording each move in turn, but that wouldn't work for a first person shooter where there are no clear turns. You could store a first person shooter by noting the exact time of each input, but that won't work for an RPG where the result of an input might be modified by the result of a random dice roll. Even the seemingly foolproof idea of taking a snapshot as often as possible isn't good enough if important information appears instantaneously and doesn't persist in any capturable form.
Interestingly this is very similar to the problem you get with networking. How does one computer ensure that another computer is made aware of the game state, without having to send that entire game state at an impractically high frequency? The typical approach ends up being a bespoke mixture of event notifications and state updates, which is probably what you'll need here.
I did this once by borrowing an idea from video compression: keyframes and intermediate frames. Basically, every few seconds you save the complete state of the world. Then, once per game update, you save all the changes to the world state that have happened since the last game update. The details (how often do you save keyframes? What exactly counts as a 'change to the world state'?) will depend on what sort of game information you need to preserve.
In our case, the world consisted of many, many game objects, most of which were holding still at any given time, so this approach saved us a lot of time and memory in recording the positions of objects that weren't moving. In yours the tradeoffs might be different.

Categories

Resources