Java Client/Server turn based help
I am trying to make a client/server turn based game. I want this to be a 2 player game. I will be using a Java applet as the client so that people can play online through a browser.
What I know so far is that I can create a server that accepts all incoming connections and create a thread to handle clients that connect. I can also write the client that will connect to the server. What I don't know is how to get two separate clients to interact with each other.
Ap开发者_开发百科plets cannot talk to each other so communication must be done via the server/threads (I assume).
I am not new to Java, but I have never done any networking before. Can someone help me out?
In my opinion the best strategy to approach a turn based game such as this, is to decide on some basic architectural approaches. Diagram out the componenents and some basic game flow diagrams.
You should put the bulk of the game engine logic in the server component. The clients should be kept as thin as possible, focusing primarily on
- Communication with the game engine
- Accepting user inputs
- Interpreting game engine responses
- Drawing the screens
Your server/game engine should be relatively stateless, yet maintain a list of current game sessions in play. Stateful SOAP web services or even HTTP Servlets would be a good choice because they maintain session for you by placing and reading session cookies in the request.
Everything web works on request response so it is by nature stateless, but certain technologies like Java servlets will help you maintain sessions so that you don't have to. No need for physically creating seperate threads, each request causes the application server to spawn a new thread of execution, while the session by nature is volatile.
On the server side I would persist all data for a particular active game in the session. In this way, your game engine will maintain the orderly communication between the two players.
- Player 1 sends end of turn request with all of the game state change information.
- Game engine interprets request, makes necessary changes to the game state.
- Player 2 sends frequent requests to check and see if it is Player 2s turn yet.
- Game engine acknowledges Player 2 request for its turn and sends the new game state in response.
- Player 2 receives the response, updates its copy of the game state making note of the changes since its last turn.
- Rinse and repeat.
You just use the server as a middle-man.
- Client A sends (writes) message to Server with attribute denoting Client B as destination
- Server receives (reads) the message and forwards (writes) the message to Client B
- Client B receives (reads) the message.
精彩评论