Java Game Networking with Kryonet: Bare-bones packet transfering - java

I'm using Opengl and Jbox2d to write a real-time 2d game in Java.
I want to start coding the networking components.
Although it uses box2d, my game is very small and I want to create a bare-bones architecture using the Kryonet library.
The program itself is a 'match game' like chess. The most logical system I can think of would be to have dedicated server that stores all player data.
PlayerA and PlayerB will connect with the dedicated server which will facilitate a TCP link between their computers.
When the match is complete, both players will communicate the resulting data back to the dedicated server, which will authenticate and then save over their respective player data.
For those familiar, Diablo2 implemented a similar setup.
I want this TCP connection to simply send the shape coordinates Vector data from the host (lets say playerA) to the client (player B) which the client will then render on its own.
Then I want the client to send mouse/keyboard data back to the host. All of the processing will be run on the host's computer.
My first question: Are there any flaws in this network logic?
My second question: How does one implement barebones server/client packet transferring (as described) using Kryonet?
Note: I have done this exact type of packet transferring in C++ using a different library. The documentation/tutorials I've found for Kryonet are terrible. Suggesting another library with good support is an acceptable answer.

I know this is an old question, and I'm sure OP has gotten their answer one way or another, but for fun I thought I'd respond anyway. This exact question has been on my mind since I've been playing around with game development using Kryonet very recently.
Some early network games, such as Bungie's Marathon (1994) seemed like they did exactly this: each player's events would be sent using UDP to other players. Thus, if a player moved or fired a shot, the player's movement or shot's direction, velocity, etc. would be sent to other players. There are some problem with this approach. If one of the player's actions are temporarily lost over the network, a player or players appeared to be out of sync with everyone else. There was no "truth" or "reconciliation" of game state in such situations.
Another approach is to have the players compute their movements and actions client-side and send the updated positions to the dedicated server. With a server receiving all player state updates, there is an opportunity to reconcile them. They also do not become out of sync permanently if some data is lost on the network.
To compare with the previous example, this would be equivalent of each player sending their positions to the server, and then having the server send each player's position to all the other players. If one of these updates gets lost for some reason, a subsequent update will correct for it. However, if only key presses are sent, a single lost keypress throws the game out of sync because all clients are computing the other clients' positions separately.
For action games you can use a hybrid approach to minimize apparent lag. I've been using Kryonet successfully in this manner for an action game. Each player sends their state to the server at every render tick (though this is probably excessive and should be optimized). The state includes position, number of shots left, health, etc. The player also sends the shots they take (starting velocity and position.)
The server simply echos these things back to clients. Whenever a shot is received by a client it is computed client-side, including whether or not the shot hits the receiving player. Since the receiving player only computes their own state, everything appears to stay in sync from their own point of view. When they are hit, they feel the hit. When they hit another player, they believe they've hit the other player. It is up to the player "receiving" a shot to update their health and send that info back to the server.
This does mean that a shot could theoretically lag or "get lost" and that a player may think their shot has hit another player, while on the other player's screen no hit occurred. But in practice, I've found this approach works well.
Here's an example (pseudocode, don't expect it to compile):
class Client {
final Array<Shot> shots;
final HashMap<String, PlayerState> players; // map of player name to state
final String playerName;
void render() {
// handle player input
// compute shot movement
// for shot in shot, shot.position = shot.position + shot.velociy * delta_t
// if one of these shots hits another player, make it appear as though they've been hit, but wait for an update in their state before we know what really happened
// if an update from another player says they died, then render their death
// if one of these shots overlaps _me_, and only if it overlaps me, deduct health from my state (other players are doing their own hit detection)
// only send _my own_ game state to server
server.sendTCP(players.get(playerName));
}
void listener(Object receivedObject) {
if(o instanceOf PlayerState) {
// update everyone else's state for me
// but ignore my own state update (since I computed it.)
PlayerState p = (PlayerState)o;
if(!p.name.equals(playerName) {
players.add(p.name, p);
}
} else if (o instanceof Shot) {
// update everyone else's shots for me
// but ignore my own shot updates (since I computed them.)
Shot s = (Shot)o;
if(!s.firedBy.equals(playerName) {
shots.add(s);
}
}
}
}
class Server {
final HashMap<String, PlayerState> players; // map of player name to
void listener(Object receivedObject) {
// compute whether anybody won based on most recent player state
// send any updates to all players
for(Connection otherPlayerCon : server.getConnections()) {
otherPlayerCon.sendTCP(o);
}
}
}
I'm sure there are pitfalls with this approach as well, and that this can be improved upon in various ways. (It would, for example, easily allow a "hacked" client to dominate, since they could always send updates that didn't factor in any damage etc. But I consider this problem out-of-scope of the question.)

Related

Should game logic be on client or server?

I'm creating a simple multiplayer turn-based game.
I can't decide where to draw the line between putting all the logic on the client or on the server.
Should the client be used just to send input to the server and print/display the responses?(This is my current solution, but seems to make the client too "stupid")
If not, how do I decide what goes on which side?
The game is very simple so I do think I could have any lag or bandwidth problems in any case.
You should always put all the game logic you can in the server, as clientside can be modified and cheat. Never trust the client.
Think of the server as the "game" and the client as the "player". Keep the client as minimal as possible. Restrict the client's influence on the game as much as you can. The client should really only be able to ask to do this and do that, it shouldn't be able to decided for itself what the result of a move be.
A real world example where the client behaved as the server was Halo 3 multiplayer where the game chose a player, part of the match, as the host (server).
Cons:
Players could lag switch other players and cause them to lag. Those players couldn't do anything and the host player just killed them and won the match.
Players chosen as hosts had bad internet and so everyone lagged to the point where a new host had to be selected.
If the host player left the game the match would stop and try to find another host (player) which wasn't always successful or take minutes.

giving timer for each turn for the player

im new to networking and currently im making a multiplayer game via java socket. so i want to ask a simple question. the game will be like this :
the game needs 3 player to start
the tile is 3x3
if all the player already join the server the game will be started
each player will be given a turn to clicking the button that contain image , example : player a clicking button 1 , and then the turn will be given to player b , player b clicking button 2 and then the turn will be given to player c , etc
MY QUESTION IS :
how do i give a timer for each player turn? what i want is if the player doesnt clicking/idle for a period time the turn will be throw to the next player. am i need to manage it in my server or client? and how?
how to handle a player that disconnected? if the player disconnect i want the turn will automatically given to the next player.
In theory, both the client and the server could handle the timer. If the server does it, it starts the timer after giving the turn to player X, and after the timer ran out, it stops the turn of player X. If you do it on client side, the client could just start the timer after receiving the turn, and then send a specific response to the server if the user did not provide input.
Now what is better? Of course the server solution. If your client disconnects, the server would keep waiting for an answer from your client, which might not even come back anymore. So you are better off doing this on server side.
As a client disconnect is a likely cause of such a time-out, you would most likely need to implement it on the server. You can do this for instance by creating a Timer, see e.g. here. Once the timer thread ends, a message could be send to the client that did not respond within time. When doing so, you should take into account that the client is unreachable, of course

Udp server too slow?

So im doing an MMO, i was progressing alot, 6 months progrramming this thing.
The problem is that i was testing offline my game, today i have the brilliant idea to port foward my server and make it online, i knew it was gonna be slighty slower, but its awful! too much lag!!! the game is unplayable.
Im managing my packets like so....
Player wants to move up, client send movePacket to the server, the server recieve it, move the player in the server and send the new position to all clients...
Each time a monster move, the server send a the new position to all clients...
I thought i was over sending packets, but i test it just with the movement of the player... it seems to have a significant delay to recieve the packet and sending them to the client....
Im I doing this whole thing wrong?
Lag is always a problem with online games. While your current method is the standard way of doing things, as your finding out the lag becomes unbearable (a common problem in 1990's and early 2000's games). The best approach to take is the same approach that almost all modern games take which is do as much as you can client side and only use your authoritative server to resolve differences between predictions that clients make. Here are a some helpful ways of reducing perceived lag:
Client-side prediction
For an MMO this may be all you need. The basic idea of client-side prediction is to locally figure out what to do. In your game when Player wants to move up he sends a packet that says [request:1 content:moveup] then BEFORE receiving a response from the server, the client displays Player moving up one (unless there you can already tell that such a move is invalid i.e. moving up would mean running into a wall). If your server is really slow then Player may also move right before receiving a response so your packet next packet may look like [request:2 content:moveright] at which point in time you show your player to the right. Keep in mind at this point Player has already moved up and right before the server has even confirmed that moving up is a valid move. Now if the server responds that the new player position after packet 1 should be up and the position after packet 2 should be right then all is well. However, if lets say another player steps happens to be above Player then the server may respond with the player in a new location. At this point Player will 'teleport' to wherever the server tells him he's supposed to be. This doesn't happen often but when it does happen it can be extremely noticeable (you've probably noticed it in commercial fps games).
Interpolation
At this point your probably fine for a MMO game but in case it isn't (or for future reference) interpolation is your next step. Here the idea is to send more data regarding rates at which values change to help make the movement of other players smoother. This is the same concept as using a taylor series in mathematics to predict values for a function. In this case you may send position as well as velocity and maybe even acceleration data for all the entities in the game. This way the new position can be calculated as x = x + v*t + 0.5*att where t is the frame rate. Again, you show the player's predicted position before the server actually confirms that this is the correct position. When the next packet from the server comes, you'll inevitably be wrong most of the time but the more rate data you send, the less you'll be off by and thus the smaller the teleportation of other entities is.
If you want a more detailed outline of how to deal with lag in online games read the mini bible on multiplayer games: http://www.gabrielgambetta.com/fast_paced_multiplayer.html

Identifying threads in game (TCP related also)

This is a school project, please do not provide any code, I am only looking for hints to guide me in the right direction.
Write and test a game server that clients subscribe to. Once subscribed, the client receives
a list of games (the same game, just different 'instances' of it) currently in play. The client may then elect to join a game or start a new
one. A game must have at least two players before actually starting. The system must support multiple clients all playing one game, or multiple clients playing multiple games.
The objective of this project is to gain experience in Java, TCP, and threading.
My current design and implementation has 2 files: server.java and client.java
The server file has 3 classes: Server, Lobby and Game
The client file has 1 class: Client.
The implementation of the "game" is trivial, I am fine with that.
Currently, the server class establishes the TCP connection with the client class.
Each time a client is instantiated, the socket is accepted in the server class, and the program continues.
Continuing on, the server class creates the lobby class.
The lobby class is where I am having trouble with. By default, I am creating 1 "game" object, and passing in the clientSocket:
game g = new game(clientSocket, playerID);
g.start();
The game class extends thread, which I think is the correct way of doing it. Each "game" will be a separate thread, so to speak, so players A and B can share 1 thread, and players C and D can start a new game with another thread.
I am new to threads, but this is the best implementation I could think of. I ruled out having multiple threads for lobby's, since that doesn't really make sense, and multiple threads for clients is pointless too, so I think multi-threading the games class is ideal.
Right now, when I create 2 instances of the client, they are both joining the same 'thread' (they are both in the same game and can talk to each other).
How am I supposed to do it so that, a new player can type "new" or whatever in the lobby and create a new "game", where it's a new thread.
I'm sure I mis-understood certain parts about threading or whatnot, but I appreciate any help.
I wouldn't map games to threads. Instead, map clients to threads. Each client will have their own thread that does work initiated by the receipt of commands from that client. When you need to create a new game, just create a new object in a shared collection of games. Track, in the client instance, which game, if any, it's associated with.
If you find you really do need a thread to manage a game, then you can create one. When a client sends a command to a particular game, just put that command on a queue of commands that's read by the thread managing that game. The game thread only needs to know which game it's managing. It can terminate itself when that game is finished.
Firstly, I would suggest you read on multiplayer game development and networking in Java (UDP/TCP). I am no game-developer but simply happenned to take a Java networking course in college and had a similar project (a networked game).
Secondly, dealing with multiple threads is proportional to complexity. You want to minimize complexity. I would suggest to abandon an "I have to find a place to use threads" mentality. (Don't force a square peg in a round hole ;))
Continuing, following through the requirements:
Write and test a game server that clients subscribe to.
IIRC, this is fairly straightforward (and you're probably past this part).
Once subscribed, the client receives a list of games (the same game, just different 'instances' of it) currently in play
This should be fairly straightforward as well since a TCP connection between the server and client have been established already.
However, there are a couple of things to understand at this point. The most important, perhaps, is that there will be a single central server that will hold information on all connected clients and existing games. This consequently means that it has to be the one to deal with the state of the system (e.g. tracking currently existing gamerooms), client requests (to create/join gamerooms), as well as updating clients with relevant info on the system's state (e.g. created/closed gamerooms).
Another consideration at this point is the scope of client's functionality in the system. A typical implementation would probably be a fat-server, thin-client architecture. Basically, this means that a client does no real processing of data (from user input) and instead relies on the server. Most of the time, then, the client is only waiting for input from user or a response from the server. On the otherhand, the server deals with the processing of data from clients, updating the system state (including individual game states), and notifying concerned client of relevant changes in the system/game state.
The client may then elect to join a game or start a new one
What actually happens here is a client sending data "I elect to join a game" or "I elect to create a game" to the server. The server acts on this and notifies concerned clients (I say concerned and not all since some clients could possibly be playing and do not need to know whether new games have spawned).
A game must have at least two players before actually starting.
-
The system must support multiple clients all playing one game, or multiple clients playing multiple games.
Again depending on the client-server architecture, either the server will be doing all the processing (fat-server, thin-client) or the clients (thin-server, fat-client) do the processing while the server mainly serves as a relay point to other clients. I have no definite (or even confident) suggestion on this, however, as I am simply overwhelmed by the sheer number of possible implementations and their consequences. Thus, I can't really encourage enough to read more on networking and game development. Individually, those 2 topics are incredibly vast, much more when combined.
Lastly, with regards to the use of threads. IIRC, dispatching separate threads for opened sockets are useful in preventing the application from getting blocked waiting for input. I don't really agree with your idea of "hosting" a game in a thread but since you're in school I can only admire your trying things out.
This may help you further: Lesson: All About Sockets. And you might perhaps also be interested in UDP.

How to manage the game state in face of the EDT?

I'm developing a real time strategy game clone on the Java platform and I have some conceptional questions about where to put and how to manage the game state. The game uses Swing/Java2D as rendering. In the current development phase, no simulation and no AI is present and only the user is able to change the state of the game (for example, build/demolish a building, add-remove production lines, assemble fleets and equipment). Therefore, the game state manipulation can be performed in the event dispatch thread without any rendering lookup. The game state is also used to display various aggregated information to the user.
However, as I need to introduce simulation (for example, building progress, population changes, fleet movements, manufacturing process, etc.), changing the game state in a Timer and EDT will surely slow down the rendering.
Lets say the simulation/AI operation is performed in every 500ms and I use SwingWorker for the computation of about 250ms in length. How can I ensure, that there is no race condition regarding the game state reads between the simulation and the possible user interaction?
I know that the result of the simulation (which is small amount of data) can be efficiently moved back to the EDT via the SwingUtilities.invokeLater() call.
The game state model seems to be too complex to be infeasible for just using immutable value classes everywhere.
Is there a relatively correct approach to eliminate this read race condition? Perhaps doing a full/partial game state cloning on every timer tick or change the living space of the game state from EDT into some other thread?
Update: (from the comments I gave)
The game operates with 13 AI controlled players, 1 human player and has about 10000 game objects (planets, buildings, equipment, research, etc.). A game object for example has the following attributes:
World (Planets, Players, Fleets, ...)
Planet (location, owner, population, type,
map, buildings, taxation, allocation, ...)
Building (location, enabled, energy, worker, health, ...)
In a scenario, the user builds a new building onto this planet. This is performed in EDT as the map and buildings collection needs to be changed. Parallel to this, a simulation is run on every 500ms to compute the energy allocation to the buildings on all game planets, which needs to traverse the buildings collection for statistics gathering. If the allocation is computed, it is submitted to the EDT and each building's energy field gets assigned.
Only human player interactions have this property, because the results of the AI computation are applied to the structures in EDT anyway.
In general, 75% of the object attributes are static and used only for rendering. The rest of it is changeable either via user interaction or simulation/AI decision. It is also ensured, that no new simulation/AI step is started until the previous one has written back all changes.
My objectives are:
Avoid delaying the user interaction, e.g. user places the building onto the planet and only after 0.5s gets the visual feedback
Avoid blocking the EDT with computation, lock wait, etc.
Avoid concurrency issues with collection traversal and modification, attribute changes
Options:
Fine grained object locking
Immutable collections
Volatile fields
Partial snapshot
All of these have advantages, disadvantages and causes to the model and the game.
Update 2: I'm talking about this game. My clone is here. The screenshots might help to imagine the rendering and data model interactions.
Update 3:
I'll try to give a small code sample for clarify my problem as it seems from the comments it is misunderstood:
List<GameObject> largeListOfGameObjects = ...
List<Building> preFilteredListOfBuildings = ...
// In EDT
public void onAddBuildingClicked() {
Building b = new Building(100 /* kW */);
largeListOfGameObjects.add(b);
preFilteredListOfBuildings.add(b);
}
// In EDT
public void paint(Graphics g) {
int y = 0;
for (Building b : preFilteredListOfBuildings) {
g.drawString(Integer.toString(b.powerAssigned), 0, y);
y += 20;
}
}
// In EDT
public void assignPowerTo(Building b, int amount) {
b.powerAssigned = amount;
}
// In simulation thread
public void distributePower() {
int sum = 0;
for (Building b : preFilteredListOfBuildings) {
sum += b.powerRequired;
}
final int alloc = sum / (preFilteredListOfBuildings.size() + 1);
for (final Building b : preFilteredListOfBuildings) {
SwingUtilities.invokeLater(=> assignPowerTo(b, alloc));
}
}
So the overlapping is between the onAddBuildingClicked() and distributePower(). Now imagine the case where you have 50 of these kind of overlappings between various parts of the game model.
This sounds like it could benefit from a client/server approach:
The player is a client - interactivity and rendering happen on that end. So the player presses a button, the request goes to the server. The reply from the server comes back, and the player's state is updated. At any point between these things happening, the screen can be re-painted, and it reflects the state of the game as the client currently knows it.
The AI is likewise a client - it's the equivalent of a bot.
The simulation is the server. It gets updates from its clients at various times and updates the state of the world, then sends out these updates to everyone as appropriate. Here's where it ties in with your situation: The simulation/AI requires a static world, and many things are happening at once. The server can simply queue up change requests and apply them before sending the updates back to the client(s). So as far as the server's concerned, the game world isn't actually changing in real time, it's changing whenever the server darn well decides it is.
Finally, on the client side, you can prevent the delay between pressing the button and seeing a result by doing some quick approximate calculations and displaying a result (so the immediate need is met) and then displaying the more correct result when the server gets around to talking to you.
Note that this does not actually have to be implemented in a TCP/IP over-the-internet sort of way, just that it helps to think of it in those terms.
Alternately, you can place the responsibility for keeping the data coherent during the simulation on a database, as they're already built with locking and coherency in mind. Something like sqlite could work as part of a non-networked solution.
Not sure I fully understand the behavior you are looking for, but it sounds like you need something like a state change thread/queue so all state changes are handled by a single thread.
Create an api, maybe like SwingUtilities.invokeLater() and/or SwingUtilities.invokeAndWait() for your state change queue to handle your state change requests.
How that is reflected in the gui I think depends on the behavior you are looking for. i.e. Can't withdraw money because current state is $0, or pop back to the user that the account was empty when the withdraw request was processed. (probably not with that terminology ;-) )
The easiest approach is to make the simulation fast enough to run in the EDT. Prefer programs that work!
For the two-thread model, what I suggest is synchronise the domain model with a rendering model. The render model should keep data on what came from the domain model.
For an update: In the simulation thread lock the render model. Traverse the render model updating where things are different from what is expected update the render model. When finished traversing, unlock the render model and schedule a repaint. Note that in this approach you don't need a bazillion listeners.
The render model can have different depths. At one extreme it might be an image and the update operation is just to replace a single reference with the new image object (this wont handle, for instance, resizing or other superficial interaction very well). You might not bother checking whether an item has change and just update eveything.
If changing the game state is fast (once you know what to change it to) you can treat the game state like other Swing models and only change or view the state in the EDT. If changing the game state is not fast, then you can either synchronize state change and do it in swing worker/timer (but not the EDT) or you can do it in separate thread that you treat similarly to the EDT (at which point you look at using a BlockingQueue to handle change requests). The last is more useful if the UI never has to retrieve information from the game state but instead has the rendering changes sent via listeners or observers.
Is it possible to incrementally update the game state and still have a model that is consistent? For example recalculate for a subset of planet/player/fleet objects in between renders/user updates.
If so, you could run incremental updates in the EDT that only calculate a small part of the state before allowing the EDT to process user inputs and render.
Following each incremental update in the EDT you would need to remember how much of the model remains to be updated and schedule a new SwingWorker on the EDT to continue this processing after any pending user inputs and rendering has been performed.
This should allow you to avoid copying or locking the game model while still keeping the user interactions responsive.
I think you shouldn't have World store any data or make changes to any objects itself, it should only be used to maintain a reference to an object and when that object needs to be changed, have the Player making the change change it directly. In this event, the only thing you need to do is synchronize each object in the game world so that when a Player is making a change, no other Player can do so. Here's an example of what I'm thinking:
Player A needs to know about a Planet, so it asks World for that Planet (how is dependent upon your implementation). World returns a reference to the Planet object Player A asked for. Player A decides to make a change, so it does so. Let's say it adds a building. The method to add a building to the Planet is synchronized so only one player can do so at a time. The building will keep track of its own construction time (if any) so the Planet's add building method would be freed up almost immediately. This way multiple players can ask for information on the same planet at the same time without affecting each other and players can add buildings almost simultaneously without much appearance of lag. If two players are looking for a place to put the building (if that is part of your game), then checking the suitability of a location will be a query not a change.
I'm sorry if this doesn't answer you're question, I'm not sure if I understood it correctly.
How about implementing a pipes and filters architecture. Pipes connect filters together and queue requests if the filter is not fast enough. Processing happens inside filters. The first filter is the AI engine while the rendering engine is implemented by a set of subsequent filters.
On every timer tick, the new dynamic world state is computed based on all the inputs (Time is also an input) and a copy inserted into the first pipe.
In the simplest case your rendering engine is implemented as a single filter. It just takes the state snapshots from the input pipe and renders it together with the static state. In a live game, the rendering engine may want to skip states if there are more than one in the pipe while if you're doing a benchmark or outputting a video you'll want to render every one.
The more filters you can decompose your rendering engine into, the better the parallelism will be. Maybe it is even possible to decompose the AI engine, e.g. you may want to separate dynamic state into fast changing and slow changing state.
This architecture gives you good parallelism without a lot of synchronization.
A problem with this architecture is that garbage collection is going to run frequently freezing all the threads every time, possible killing any advantage gained from multi-threading.
It looks like you need a priorityqueue to put the updates to the model on, in which updates frmo the user have priority over the updates from the simulation and other inputs. What I hear you saying is that the user always needs immediate feedback over his actions wheras the other inputs (simulation, otherwise) could have workers that may take longer than one simulation step.
Then synchronize on the priorityqueue.

Categories