title: Synchronize Game logic on server and client
body: <p>I'm creating a simple Network game in Java, where the player can move Blocks around using the keyboard keys. The game will run on a local Server, and has a basic rule:</p>
  
  <p><code>Each block will move automatically at 1 FPS rate, but the **user can send several move
  commands** in this 1 second interval, thus updating the block position.</code></p>
  
  <p>The code is almost complete, but í'm having trouble to synchronize things between server and client. Here's some code/description of what i need to understand better:</p>
  
  <h2>Basic classes</h2>
  
  <pre><code>class Server{
  
      ServerSocket server = new ServerSocket(port);
  
      while (listening) {
          Socket client = server.accept();
          new Thread(new ClientHandler(client)).start();
      }
  }
  
  class Game implements Runnable {
  
      public void run() { 
          while (! gameOver)
              tick();
      }   
  }
  </code></pre>
  
  <h2>Now the problem</h2>
  
  <pre><code>class ClientHandler implements Runnable
  {
      Game game;
      public ClientHandler(Socket client)
      {   
          this.client = client;
  
          //start game which runs at 1 FPS
          long FPS = 1000L;
          Timer timer = new Timer();
          timer.schedule(new Game(FPS), 0L, FPS);
      }
  
      public void run()
      {
          /** Game is already running, needs to:
          *
          * 1 - Take any GameInput object from the user and update the game
          * 2 - Send a GameState object to the user 
          * 3 - Client will receive it and render on screen,
          *     (hopefully in a synch state with the server)
          */ 
  
          while ( ! game.gameOver)
          {
              //ObjectInputStream ois = ...;
  
              // Line A
              GameInput command = ois.readObject();
  
              // Line B
              //GameState state = game.update(command);
  
              //ObjectOutputStream oos = ...;
  
             // Line C
              oos.writeObject(state);
          }
      }
  }
  </code></pre>
  
  <p>What i need to understand better is how to handle <code>Line A</code>, <code>Line B</code> and <code>Line C</code>.
  To be more precise:</p>
  
  <p>1 - What's a good way of update the game Thread in a safe way?</p>
  
  <p>2 - How do i handle multiple commands? A Queue maybe?</p>
  
  <p>2 - How can i ensure that client and server will be in synch?</p>
  
  <p>I´m new to Networking programming, so thanks for any help!</p>