Skip to content

Java client

Starter code for your client: WBP SE06 Gameserver ISY Java Client.

Build and run

  • Uses only Java 8 features. Run it with Java 21 or newer.
  • Start the game server first.
git clone "https://dev.azure.com/ZernikeCollabSpace/WBP%20SE06%20Gameserver%20ISY/_git/WBP%20SE06%20Gameserver%20ISY%20Java%20Client" java-client
cd java-client
javac -d out $(find src -name "*.java")
java -cp out isy.client.Main ws://localhost:8080/ws <name>

Main plays Tic-Tac-Toe. It always picks the first free spot.

Files

File What it does
GameClient Sends commands. Matches answers to requests. Passes events on.
commands/Session, Lobby, Game One class per command
events/EventRouter Runs your code when an event comes in
protocol/ProtocolLine Reads one line
protocol/Response Reads an answer (OK or ERR)
transport/WebSocketTransport The connection
Main Example game

Send a command

client.send(new Lobby.Subscribe(game));
client.send(new Game.Move(m, move));
  • game, m, move and name are the placeholders <game>, <m>, <move> and <name>.
  • The client picks <id> for you.

Wait for the answer:

client.send(new Session.Login(name)).thenAccept(res -> {
    if (res.ok()) {
        System.out.println("session token: " + res.get("session_token"));
    } else {
        System.out.println("error: " + res.code());
    }
});

React to events

client.events().group("game")
    .on("your_turn", evt -> client.send(new Game.Move(evt.subject(), move)))
    .on("result", evt -> System.out.println(evt.args().raw()));
  • group("game").on("your_turn", ...) runs for game.your_turn.
  • onAny(...) runs for every event in that group you didn't handle.
  • evt.subject() is the match ID.
  • evt.args().get("move") gives one field of the JSON data as text, like "4".
  • evt.args().json() gives the whole JSON object as a Map. evt.args().raw() gives the JSON text.
  • protocol/Json reads and writes JSON without a library.

Add a command

  1. Add a record to Session, Lobby or Game. The command list shows the line it must send.
  2. Give it verb() and, if needed, subject() and args(). Build args() with Json.object("name", value, ...).

Watch out

  • Your event code runs on the connection's thread.
  • Don't call .join() on an answer inside event code. It will freeze. Use .thenAccept(...).
  • Check res.ok() before you read res.get("session_token"). On an error, read res.get("reason") instead.
  • client.closed() completes when the connection ends. Answers you are still waiting for fail. Reconnect from there.