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¶
game,m,moveandnameare 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 forgame.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 aMap.evt.args().raw()gives the JSON text.protocol/Jsonreads and writes JSON without a library.
Add a command¶
- Add a
recordtoSession,LobbyorGame. The command list shows the line it must send. - Give it
verb()and, if needed,subject()andargs(). Buildargs()withJson.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 readres.get("session_token"). On an error, readres.get("reason")instead. client.closed()completes when the connection ends. Answers you are still waiting for fail. Reconnect from there.