mirror of
https://github.com/2OOP/pism.git
synced 2026-02-04 10:54:51 +00:00
Partial server refactor
This commit is contained in:
@@ -17,12 +17,10 @@ import org.toop.framework.gameFramework.model.player.Player;
|
|||||||
import org.toop.framework.networking.connection.clients.TournamentNetworkingClient;
|
import org.toop.framework.networking.connection.clients.TournamentNetworkingClient;
|
||||||
import org.toop.framework.networking.connection.events.NetworkEvents;
|
import org.toop.framework.networking.connection.events.NetworkEvents;
|
||||||
import org.toop.framework.networking.connection.types.NetworkingConnector;
|
import org.toop.framework.networking.connection.types.NetworkingConnector;
|
||||||
import org.toop.framework.game.games.reversi.BitboardReversi;
|
|
||||||
import org.toop.framework.game.games.tictactoe.BitboardTicTacToe;
|
|
||||||
import org.toop.framework.game.players.ArtificialPlayer;
|
import org.toop.framework.game.players.ArtificialPlayer;
|
||||||
import org.toop.framework.game.players.OnlinePlayer;
|
import org.toop.framework.game.players.OnlinePlayer;
|
||||||
import org.toop.framework.game.players.RandomAI;
|
import org.toop.framework.game.players.RandomAI;
|
||||||
import org.toop.framework.networking.server.MasterServer;
|
import org.toop.framework.networking.server.gateway.NettyGatewayServer;
|
||||||
import org.toop.local.AppContext;
|
import org.toop.local.AppContext;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -33,7 +31,7 @@ import java.util.concurrent.TimeUnit;
|
|||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
|
||||||
public final class Server {
|
public final class Server {
|
||||||
private MasterServer masterServer;
|
private NettyGatewayServer nettyGatewayServer;
|
||||||
|
|
||||||
private String user = "";
|
private String user = "";
|
||||||
private long clientId = -1;
|
private long clientId = -1;
|
||||||
@@ -68,7 +66,7 @@ public final class Server {
|
|||||||
|
|
||||||
// Server has to deal with ALL network related listen events. This "server" can then interact with the manager to make stuff happen.
|
// Server has to deal with ALL network related listen events. This "server" can then interact with the manager to make stuff happen.
|
||||||
// This prevents data races where events get sent to the game manager but the manager isn't ready yet.
|
// This prevents data races where events get sent to the game manager but the manager isn't ready yet.
|
||||||
public Server(String ip, String port, String user, MasterServer masterServer) {
|
public Server(String ip, String port, String user, NettyGatewayServer nettyGatewayServer) {
|
||||||
if (ip.split("\\.").length < 4) {
|
if (ip.split("\\.").length < 4) {
|
||||||
new ErrorPopup("\"" + ip + "\" " + AppContext.getString("is-not-a-valid-ip-address"));
|
new ErrorPopup("\"" + ip + "\" " + AppContext.getString("is-not-a-valid-ip-address"));
|
||||||
return;
|
return;
|
||||||
@@ -88,7 +86,7 @@ public final class Server {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.masterServer = masterServer;
|
this.nettyGatewayServer = nettyGatewayServer;
|
||||||
|
|
||||||
final int reconnectAttempts = 10;
|
final int reconnectAttempts = 10;
|
||||||
|
|
||||||
@@ -288,8 +286,8 @@ public final class Server {
|
|||||||
stopScheduler();
|
stopScheduler();
|
||||||
connectFlow.unsubscribeAll();
|
connectFlow.unsubscribeAll();
|
||||||
|
|
||||||
if (masterServer != null) {
|
if (nettyGatewayServer != null) {
|
||||||
masterServer.stop();
|
nettyGatewayServer.stop();
|
||||||
}
|
}
|
||||||
|
|
||||||
WidgetContainer.getCurrentView().transitionPrevious();
|
WidgetContainer.getCurrentView().transitionPrevious();
|
||||||
|
|||||||
@@ -9,7 +9,8 @@ import javafx.geometry.Pos;
|
|||||||
import org.toop.framework.game.games.reversi.BitboardReversi;
|
import org.toop.framework.game.games.reversi.BitboardReversi;
|
||||||
import org.toop.framework.game.games.tictactoe.BitboardTicTacToe;
|
import org.toop.framework.game.games.tictactoe.BitboardTicTacToe;
|
||||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
import org.toop.framework.networking.server.MasterServer;
|
import org.toop.framework.networking.server.gateway.NettyGatewayServer;
|
||||||
|
import org.toop.framework.networking.server.stores.TurnBasedGameTypeStore;
|
||||||
|
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
@@ -31,11 +32,12 @@ public class OnlineView extends ViewWidget {
|
|||||||
});
|
});
|
||||||
|
|
||||||
var localHostButton = Primitive.button("host!", () -> {
|
var localHostButton = Primitive.button("host!", () -> {
|
||||||
var games = new ConcurrentHashMap<String, Class<? extends TurnBasedGame>>();
|
|
||||||
games.put("tic-tac-toe", BitboardTicTacToe.class);
|
|
||||||
games.put("reversi", BitboardReversi.class);
|
|
||||||
|
|
||||||
var a = new MasterServer(6666, games, Duration.ofSeconds(10));
|
var tps = new TurnBasedGameTypeStore();
|
||||||
|
tps.register("tic-tac-toe", BitboardTicTacToe::new);
|
||||||
|
tps.register("reversi", BitboardReversi::new);
|
||||||
|
|
||||||
|
var a = new NettyGatewayServer(6666, tps, Duration.ofSeconds(10));
|
||||||
|
|
||||||
new Thread(() -> {
|
new Thread(() -> {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -3,18 +3,18 @@ package org.toop.framework.game.players;
|
|||||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
import org.toop.framework.gameFramework.model.player.AbstractPlayer;
|
import org.toop.framework.gameFramework.model.player.AbstractPlayer;
|
||||||
import org.toop.framework.gameFramework.model.player.Player;
|
import org.toop.framework.gameFramework.model.player.Player;
|
||||||
import org.toop.framework.networking.server.User;
|
import org.toop.framework.networking.server.client.NettyClient;
|
||||||
|
|
||||||
import java.util.concurrent.CompletableFuture;
|
import java.util.concurrent.CompletableFuture;
|
||||||
import java.util.concurrent.ExecutionException;
|
import java.util.concurrent.ExecutionException;
|
||||||
|
|
||||||
public class ServerPlayer extends AbstractPlayer {
|
public class ServerPlayer extends AbstractPlayer {
|
||||||
private User user;
|
private NettyClient client;
|
||||||
private CompletableFuture<Long> lastMove;
|
private CompletableFuture<Long> lastMove;
|
||||||
|
|
||||||
public ServerPlayer(User user) {
|
public ServerPlayer(NettyClient client) {
|
||||||
super(user.name());
|
super(client.name());
|
||||||
this.user = user;
|
this.client = client;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setMove(long move) {
|
public void setMove(long move) {
|
||||||
@@ -30,7 +30,7 @@ public class ServerPlayer extends AbstractPlayer {
|
|||||||
public long getMove(TurnBasedGame game) {
|
public long getMove(TurnBasedGame game) {
|
||||||
lastMove = new CompletableFuture<>();
|
lastMove = new CompletableFuture<>();
|
||||||
System.out.println("Sending yourturn");
|
System.out.println("Sending yourturn");
|
||||||
user.sendMessage("SVR GAME YOURTURN {TURNMESSAGE: \"<bericht voor deze beurt>\"}\n");
|
client.send("SVR GAME YOURTURN {TURNMESSAGE: \"<bericht voor deze beurt>\"}\n");
|
||||||
try {
|
try {
|
||||||
return lastMove.get();
|
return lastMove.get();
|
||||||
} catch (InterruptedException | ExecutionException e) {
|
} catch (InterruptedException | ExecutionException e) {
|
||||||
|
|||||||
@@ -1,155 +0,0 @@
|
|||||||
package org.toop.framework.networking.server;
|
|
||||||
|
|
||||||
import io.netty.channel.ChannelHandlerContext;
|
|
||||||
import io.netty.channel.SimpleChannelInboundHandler;
|
|
||||||
import org.apache.maven.surefire.shared.utils.StringUtils;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Iterator;
|
|
||||||
import java.util.LinkedList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
public class ConnectionHandler extends SimpleChannelInboundHandler<String> {
|
|
||||||
|
|
||||||
private final User user;
|
|
||||||
private final Server server;
|
|
||||||
|
|
||||||
public ConnectionHandler(User user, Server server) {
|
|
||||||
this.user = user;
|
|
||||||
this.server = server;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String returnQuotedString(Iterator<String> strings) { // TODO more places this could be useful
|
|
||||||
return "\"" + StringUtils.join(strings, "\",\"") + "\"";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void channelActive(ChannelHandlerContext ctx) {
|
|
||||||
ctx.writeAndFlush("WELCOME " + user.id() + "\n");
|
|
||||||
|
|
||||||
user.setCtx(ctx);
|
|
||||||
server.addUser(user); // TODO set correct name on login
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected void channelRead0(ChannelHandlerContext ctx, String msg) {
|
|
||||||
|
|
||||||
IO.println(msg);
|
|
||||||
|
|
||||||
ParsedMessage p = parse(msg);
|
|
||||||
if (p == null) return;
|
|
||||||
|
|
||||||
IO.println(p.command() + " " + Arrays.toString(p.args()));
|
|
||||||
|
|
||||||
switch (p.command()) {
|
|
||||||
case "ping" -> ctx.writeAndFlush("PONG\n");
|
|
||||||
case "login" -> handleLogin(p);
|
|
||||||
case "get" -> handleGet(p);
|
|
||||||
case "subscribe" -> handleSubscribe(p);
|
|
||||||
case "move" -> handleMove(p);
|
|
||||||
case "challenge" -> handleChallenge(p);
|
|
||||||
case "message" -> handleMessage(p);
|
|
||||||
case "help" -> handleHelp(p);
|
|
||||||
default -> ctx.writeAndFlush("ERROR Unknown command\n");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// DO NOT INVERT
|
|
||||||
private boolean hasArgs(String... args) {
|
|
||||||
return (args.length >= 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void handleLogin(ParsedMessage p) {
|
|
||||||
if (!hasArgs(p.args())) return;
|
|
||||||
|
|
||||||
user.setName(p.args()[0]);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void handleGet(ParsedMessage p) {
|
|
||||||
if (!hasArgs(p.args())) return;
|
|
||||||
|
|
||||||
switch (p.args()[0]) {
|
|
||||||
case "playerlist" -> {
|
|
||||||
var names = server.onlineUsers().stream().map(ServerUser::name).iterator();
|
|
||||||
user.ctx().writeAndFlush("SVR PLAYERLIST " + returnQuotedString(names) + "\n");
|
|
||||||
}
|
|
||||||
case "gamelist" -> {
|
|
||||||
var names = server.gameTypes().stream().iterator();
|
|
||||||
user.ctx().writeAndFlush("SVR GAMELIST " + returnQuotedString(names) + "\n");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void handleSubscribe(ParsedMessage p) {
|
|
||||||
// TODO
|
|
||||||
}
|
|
||||||
|
|
||||||
private void handleHelp(ParsedMessage p) {
|
|
||||||
// TODO
|
|
||||||
}
|
|
||||||
|
|
||||||
private void handleMessage(ParsedMessage p) {
|
|
||||||
// TODO
|
|
||||||
}
|
|
||||||
|
|
||||||
private void handleChallenge(ParsedMessage p) {
|
|
||||||
if (!hasArgs(p.args())) return;
|
|
||||||
if (p.args().length < 2) return;
|
|
||||||
|
|
||||||
if (p.args()[0].equalsIgnoreCase("accept")) {
|
|
||||||
try {
|
|
||||||
long id = Long.parseLong(p.args()[1]);
|
|
||||||
|
|
||||||
if (id <= 0) {
|
|
||||||
user.sendMessage("ERR id must be a positive number \n");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
server.acceptChallenge(id);
|
|
||||||
|
|
||||||
} catch (NumberFormatException e) {
|
|
||||||
user.sendMessage("ERR id is not a valid number or too big \n");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
server.challengeUser(user.name(), p.args()[0], p.args()[1]);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void handleMove(ParsedMessage p) {
|
|
||||||
if(!hasArgs(p.args())) return;
|
|
||||||
|
|
||||||
// TODO check if not number
|
|
||||||
user.serverPlayer().setMove(1L << Integer.parseInt(p.args()[0]));
|
|
||||||
}
|
|
||||||
|
|
||||||
private ParsedMessage parse(String msg) {
|
|
||||||
// TODO, what if empty string.
|
|
||||||
|
|
||||||
if (msg.isEmpty()) return null;
|
|
||||||
|
|
||||||
msg = msg.trim().toLowerCase();
|
|
||||||
|
|
||||||
List<String> parts = new LinkedList<>(List.of(msg.split(" ")));
|
|
||||||
|
|
||||||
if (parts.size() > 1) {
|
|
||||||
String command = parts.removeFirst();
|
|
||||||
return new ParsedMessage(command, parts.toArray(String[]::new));
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
return new ParsedMessage(msg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
|
|
||||||
cause.printStackTrace();
|
|
||||||
ctx.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void channelInactive(ChannelHandlerContext ctx) {
|
|
||||||
server.removeUser(user);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -3,39 +3,40 @@ package org.toop.framework.networking.server;
|
|||||||
import org.toop.framework.game.gameThreads.ServerThreadBehaviour;
|
import org.toop.framework.game.gameThreads.ServerThreadBehaviour;
|
||||||
import org.toop.framework.gameFramework.GameState;
|
import org.toop.framework.gameFramework.GameState;
|
||||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
|
import org.toop.framework.networking.server.client.NettyClient;
|
||||||
|
|
||||||
public class Game implements OnlineGame<TurnBasedGame> {
|
public class Game implements OnlineGame<TurnBasedGame> {
|
||||||
|
|
||||||
private long id;
|
private long id;
|
||||||
private User[] users;
|
private NettyClient[] clients;
|
||||||
private TurnBasedGame game;
|
private TurnBasedGame game;
|
||||||
private ServerThreadBehaviour gameThread;
|
private ServerThreadBehaviour gameThread;
|
||||||
|
|
||||||
public Game(TurnBasedGame game, User... users) {
|
public Game(TurnBasedGame game, NettyClient... clients) {
|
||||||
this.game = game;
|
this.game = game;
|
||||||
this.gameThread = new ServerThreadBehaviour(
|
this.gameThread = new ServerThreadBehaviour(
|
||||||
game,
|
game,
|
||||||
(pair) -> notifyMoveMade(pair.getLeft(), pair.getRight()),
|
(pair) -> notifyMoveMade(pair.getLeft(), pair.getRight()),
|
||||||
(pair) -> notifyGameEnd(pair.getLeft(), pair.getRight())
|
(pair) -> notifyGameEnd(pair.getLeft(), pair.getRight())
|
||||||
);
|
);
|
||||||
this.users = users;
|
this.clients = clients;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void notifyMoveMade(String speler, int move){
|
private void notifyMoveMade(String speler, int move){
|
||||||
for (User user : users) {
|
for (NettyClient client : clients) {
|
||||||
user.sendMessage(String.format("SVR GAME MOVE {PLAYER: \"%s\", MOVE: \"%s\", DETAILS: \"<reactie spel op zet>\"}\n", speler, move));
|
client.send(String.format("SVR GAME MOVE {PLAYER: \"%s\", MOVE: \"%s\", DETAILS: \"<reactie spel op zet>\"}\n", speler, move));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void notifyGameEnd(GameState state, int winner){
|
private void notifyGameEnd(GameState state, int winner){
|
||||||
if (state == GameState.DRAW){
|
if (state == GameState.DRAW){
|
||||||
for (User user : users) {
|
for (NettyClient client : clients) {
|
||||||
user.sendMessage(String.format("SVR GAME DRAW {PLAYERONESCORE: \"<score speler1>\", PLAYERTWOSCORE: \"<score speler2>\", COMMENT: \"Client disconnected\"}\n"));
|
client.send(String.format("SVR GAME DRAW {PLAYERONESCORE: \"<score speler1>\", PLAYERTWOSCORE: \"<score speler2>\", COMMENT: \"NettyClient disconnected\"}\n"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else{
|
else{
|
||||||
users[winner].sendMessage(String.format("SVR GAME WIN {PLAYERONESCORE: \"<score speler1>\", PLAYERTWOSCORE: \"<score speler2>\", COMMENT: \"Client disconnected\"}\n"));
|
clients[winner].send(String.format("SVR GAME WIN {PLAYERONESCORE: \"<score speler1>\", PLAYERTWOSCORE: \"<score speler2>\", COMMENT: \"NettyClient disconnected\"}\n"));
|
||||||
users[(winner + 1)%2].sendMessage(String.format("SVR GAME LOSS {PLAYERONESCORE: \"<score speler1>\", PLAYERTWOSCORE: \"<score speler2>\", COMMENT: \"Client disconnected\"}\n"));
|
clients[(winner + 1)%2].send(String.format("SVR GAME LOSS {PLAYERONESCORE: \"<score speler1>\", PLAYERTWOSCORE: \"<score speler2>\", COMMENT: \"NettyClient disconnected\"}\n"));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -51,8 +52,8 @@ public class Game implements OnlineGame<TurnBasedGame> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public User[] users() {
|
public NettyClient[] users() {
|
||||||
return users;
|
return clients;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -1,28 +0,0 @@
|
|||||||
package org.toop.framework.networking.server;
|
|
||||||
|
|
||||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
|
||||||
|
|
||||||
import java.lang.reflect.InvocationTargetException;
|
|
||||||
|
|
||||||
public class GameDefinition<T> {
|
|
||||||
private final String name;
|
|
||||||
private final Class<T> game;
|
|
||||||
|
|
||||||
public GameDefinition(String name, Class<T> game) {
|
|
||||||
this.name = name;
|
|
||||||
this.game = game;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String name() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public T create(String... users) {
|
|
||||||
try {
|
|
||||||
return game.getDeclaredConstructor().newInstance(users);
|
|
||||||
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -3,6 +3,6 @@ package org.toop.framework.networking.server;
|
|||||||
public interface GameServer {
|
public interface GameServer {
|
||||||
// List<?> gameTypes();
|
// List<?> gameTypes();
|
||||||
// List<?> ongoingGames();
|
// List<?> ongoingGames();
|
||||||
// void startGame(String gameType, User... users);
|
// void startGame(String gameType, NettyClient... users);
|
||||||
// String[] onlineUsers();
|
// String[] onlineUsers();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
package org.toop.framework.networking.server;
|
|
||||||
|
|
||||||
public interface MessageStore {
|
|
||||||
void add(String message);
|
|
||||||
String get();
|
|
||||||
void reset();
|
|
||||||
}
|
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
package org.toop.framework.networking.server;
|
package org.toop.framework.networking.server;
|
||||||
|
|
||||||
|
import org.toop.framework.networking.server.client.NettyClient;
|
||||||
|
|
||||||
public interface OnlineGame<T> {
|
public interface OnlineGame<T> {
|
||||||
long id();
|
long id();
|
||||||
T game();
|
T game();
|
||||||
User[] users();
|
NettyClient[] users();
|
||||||
void start();
|
void start();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +0,0 @@
|
|||||||
package org.toop.framework.networking.server;
|
|
||||||
|
|
||||||
public class Parser {
|
|
||||||
}
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
package org.toop.framework.networking.server;
|
|
||||||
|
|
||||||
public interface ServableGame {
|
|
||||||
}
|
|
||||||
@@ -2,27 +2,41 @@ package org.toop.framework.networking.server;
|
|||||||
|
|
||||||
import org.toop.framework.game.players.ServerPlayer;
|
import org.toop.framework.game.players.ServerPlayer;
|
||||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
|
import org.toop.framework.networking.server.challenges.gamechallenge.GameChallenge;
|
||||||
|
import org.toop.framework.networking.server.challenges.gamechallenge.GameChallengeTimer;
|
||||||
|
import org.toop.framework.networking.server.client.NettyClient;
|
||||||
|
import org.toop.framework.networking.server.stores.ClientStore;
|
||||||
|
import org.toop.framework.networking.server.stores.TurnBasedGameStore;
|
||||||
|
import org.toop.framework.networking.server.stores.TurnBasedGameTypeStore;
|
||||||
import org.toop.framework.utils.ImmutablePair;
|
import org.toop.framework.utils.ImmutablePair;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
|
||||||
import java.util.concurrent.*;
|
import java.util.concurrent.*;
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
|
|
||||||
public class Server implements GameServer {
|
public class Server implements GameServer {
|
||||||
|
|
||||||
final private Map<String, Class<? extends TurnBasedGame>> gameTypes;
|
final private TurnBasedGameTypeStore gameTypesStore;
|
||||||
final private Map<Long, User> users = new ConcurrentHashMap<>();
|
final private ClientStore<Long, NettyClient> clientStore;
|
||||||
final private List<GameChallenge> gameChallenges = new CopyOnWriteArrayList<>();
|
final private List<GameChallenge> gameChallenges = new CopyOnWriteArrayList<>();
|
||||||
final private List<OnlineGame<TurnBasedGame>> games = new CopyOnWriteArrayList<>();
|
final private TurnBasedGameStore gameStore;
|
||||||
|
|
||||||
final private Duration challengeDuration;
|
final private Duration challengeDuration;
|
||||||
final private ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
|
final private ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
|
||||||
|
|
||||||
public Server(Map<String, Class<? extends TurnBasedGame>> gameTypes, Duration challengeDuration) {
|
public Server(
|
||||||
this.gameTypes = gameTypes;
|
Duration challengeDuration,
|
||||||
|
TurnBasedGameTypeStore turnBasedGameTypeStore,
|
||||||
|
ClientStore<Long, NettyClient> clientStore,
|
||||||
|
TurnBasedGameStore gameStore
|
||||||
|
|
||||||
|
) {
|
||||||
|
this.gameTypesStore = turnBasedGameTypeStore;
|
||||||
this.challengeDuration = challengeDuration;
|
this.challengeDuration = challengeDuration;
|
||||||
|
this.clientStore = clientStore;
|
||||||
|
this.gameStore = gameStore;
|
||||||
|
|
||||||
scheduler.schedule(this::serverTask, 0, TimeUnit.MILLISECONDS);
|
scheduler.schedule(this::serverTask, 0, TimeUnit.MILLISECONDS);
|
||||||
}
|
}
|
||||||
@@ -32,51 +46,51 @@ public class Server implements GameServer {
|
|||||||
scheduler.schedule(this::serverTask, 500, TimeUnit.MILLISECONDS);
|
scheduler.schedule(this::serverTask, 500, TimeUnit.MILLISECONDS);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addUser(User user) {
|
public void addUser(NettyClient client) {
|
||||||
users.putIfAbsent(user.id(), user);
|
clientStore.add(client);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void removeUser(User user) {
|
public void removeUser(NettyClient client) {
|
||||||
users.remove(user.id());
|
clientStore.remove(client.id());
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<String> gameTypes() {
|
public List<String> gameTypes() {
|
||||||
return gameTypes.keySet().stream().toList();
|
return new ArrayList<>(gameTypesStore.all().keySet());
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<OnlineGame<TurnBasedGame>> ongoingGames() {
|
public List<OnlineGame<TurnBasedGame>> ongoingGames() {
|
||||||
return games;
|
return gameStore.all().stream().toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
public User getUser(String username) {
|
public NettyClient getUser(String username) {
|
||||||
return users.values().stream().filter(e -> e.name().equalsIgnoreCase(username)).findFirst().orElse(null);
|
return clientStore.all().stream().filter(e -> e.name().equalsIgnoreCase(username)).findFirst().orElse(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public User getUser(long id) {
|
public NettyClient getUser(long id) {
|
||||||
return users.get(id);
|
return clientStore.get(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void challengeUser(String fromUser, String toUser, String gameType) {
|
public void challengeUser(String fromUser, String toUser, String gameType) {
|
||||||
|
|
||||||
User from = getUser(fromUser);
|
NettyClient from = getUser(fromUser);
|
||||||
if (from == null) {
|
if (from == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!gameTypes.containsKey(gameType)) {
|
if (!gameTypesStore.all().containsKey(gameType)) {
|
||||||
from.sendMessage("ERR gametype not found \n");
|
from.send("ERR gametype not found \n");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
User to = getUser(toUser);
|
NettyClient to = getUser(toUser);
|
||||||
if (to == null) {
|
if (to == null) {
|
||||||
from.sendMessage("ERR user not found \n");
|
from.send("ERR user not found \n");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var ch = new GameChallenge(from, to, gameType, new GameChallengeTimer(challengeDuration));
|
var ch = new GameChallenge(from, to, gameType, new GameChallengeTimer(challengeDuration));
|
||||||
|
|
||||||
to.sendMessage(
|
to.send(
|
||||||
"SVR GAME CHALLENGE {CHALLENGER: \"%s\", CHALLENGENUMBER: \"%s\", GAMETYPE: \"%s\"} \n"
|
"SVR GAME CHALLENGE {CHALLENGER: \"%s\", CHALLENGENUMBER: \"%s\", GAMETYPE: \"%s\"} \n"
|
||||||
.formatted(from.name(), ch.id(), gameType)
|
.formatted(from.name(), ch.id(), gameType)
|
||||||
);
|
);
|
||||||
@@ -90,13 +104,13 @@ public class Server implements GameServer {
|
|||||||
gameChallenges.addLast(ch);
|
gameChallenges.addLast(ch);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void warnUserExpiredChallenge(User user, long challengeId) {
|
private void warnUserExpiredChallenge(NettyClient client, long challengeId) {
|
||||||
user.sendMessage("SVR GAME CHALLENGE CANCELLED {CHALLENGENUMBER: \"" + challengeId + "\"}" + "\n");
|
client.send("SVR GAME CHALLENGE CANCELLED {CHALLENGENUMBER: \"" + challengeId + "\"}" + "\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean isValidChallenge(GameChallenge gameChallenge) {
|
private boolean isValidChallenge(GameChallenge gameChallenge) {
|
||||||
for (var user : gameChallenge.getUsers()) {
|
for (var user : gameChallenge.getUsers()) {
|
||||||
if (users.get(user.id()) == null) {
|
if (clientStore.get(user.id()) == null) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -140,43 +154,40 @@ public class Server implements GameServer {
|
|||||||
return gameChallenges;
|
return gameChallenges;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void startGame(String gameType, User... users) {
|
public void startGame(String gameType, NettyClient... clients) {
|
||||||
if (!gameTypes.containsKey(gameType)) return;
|
if (!gameTypesStore.all().containsKey(gameType)) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
ServerPlayer[] players = new ServerPlayer[users.length];
|
ServerPlayer[] players = new ServerPlayer[clients.length];
|
||||||
var game = new Game(gameTypes.get(gameType).getDeclaredConstructor().newInstance(), users);
|
var game = new Game(gameTypesStore.create(gameType), clients);
|
||||||
|
|
||||||
for (int i = 0; i < users.length; i++) {
|
for (int i = 0; i < clients.length; i++) {
|
||||||
players[i] = new ServerPlayer(users[i]);
|
players[i] = new ServerPlayer(clients[i]);
|
||||||
users[i].addGame(new ImmutablePair<>(game, players[i]));
|
clients[i].addGame(new ImmutablePair<>(game, players[i]));
|
||||||
}
|
}
|
||||||
System.out.println("Starting Game");
|
System.out.println("Starting Game");
|
||||||
|
|
||||||
game.game().init(players);
|
game.game().init(players);
|
||||||
games.addLast(game);
|
gameStore.add(game);
|
||||||
|
|
||||||
users[0].sendMessage(String.format("SVR GAME MATCH {PLAYERTOMOVE: \"%s\", GAMETYPE: \"%s\", OPPONENT: \"%s\"}\n",
|
clients[0].send(String.format("SVR GAME MATCH {PLAYERTOMOVE: \"%s\", GAMETYPE: \"%s\", OPPONENT: \"%s\"}\n",
|
||||||
users[0].name(),
|
clients[0].name(),
|
||||||
gameType,
|
gameType,
|
||||||
users[1].name()));
|
clients[1].name()));
|
||||||
users[1].sendMessage(String.format("SVR GAME MATCH {PLAYERTOMOVE: \"%s\", GAMETYPE: \"%s\", OPPONENT: \"%s\"}\n",
|
clients[1].send(String.format("SVR GAME MATCH {PLAYERTOMOVE: \"%s\", GAMETYPE: \"%s\", OPPONENT: \"%s\"}\n",
|
||||||
users[0].name(),
|
clients[0].name(),
|
||||||
gameType,
|
gameType,
|
||||||
users[0].name()));
|
clients[0].name()));
|
||||||
game.start();
|
game.start();
|
||||||
} catch (Exception ignored) {}
|
} catch (Exception ignored) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<User> onlineUsers() {
|
public List<NettyClient> onlineUsers() {
|
||||||
return users.values().stream().toList();
|
return clientStore.all().stream().toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void closeServer() {
|
public void closeServer() {
|
||||||
scheduler.shutdown();
|
scheduler.shutdown();
|
||||||
gameChallenges.clear();
|
gameChallenges.clear();
|
||||||
games.clear();
|
|
||||||
users.clear();
|
|
||||||
gameTypes.clear();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
package org.toop.framework.networking.server;
|
|
||||||
|
|
||||||
import java.util.Queue;
|
|
||||||
|
|
||||||
public class ServerMessageStore implements MessageStore {
|
|
||||||
|
|
||||||
Queue<String> messageQueue;
|
|
||||||
|
|
||||||
public ServerMessageStore(Queue<String> messageQueue) {
|
|
||||||
this.messageQueue = messageQueue;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void add(String message) {
|
|
||||||
messageQueue.offer(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String get() {
|
|
||||||
return messageQueue.poll();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void reset() {
|
|
||||||
messageQueue.clear();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
package org.toop.framework.networking.server;
|
|
||||||
|
|
||||||
import org.toop.framework.game.players.ServerPlayer;
|
|
||||||
import org.toop.framework.utils.Pair;
|
|
||||||
|
|
||||||
public interface ServerUser {
|
|
||||||
long id();
|
|
||||||
String name();
|
|
||||||
Game game();
|
|
||||||
ServerPlayer serverPlayer();
|
|
||||||
void addGame(Pair<Game, ServerPlayer> gamePair);
|
|
||||||
void removeGame();
|
|
||||||
void setName(String name);
|
|
||||||
void sendMessage(String message);
|
|
||||||
}
|
|
||||||
@@ -1,18 +1,20 @@
|
|||||||
package org.toop.framework.networking.server;
|
package org.toop.framework.networking.server.challenges.gamechallenge;
|
||||||
|
|
||||||
import org.toop.framework.SnowflakeGenerator;
|
import org.toop.framework.SnowflakeGenerator;
|
||||||
|
import org.toop.framework.networking.server.client.NettyClient;
|
||||||
|
import org.toop.framework.utils.SimpleTimer;
|
||||||
|
|
||||||
public class GameChallenge {
|
public class GameChallenge {
|
||||||
private final long id = SnowflakeGenerator.nextId(); // I don't need this, but the tournament server uses it...
|
private final long id = SnowflakeGenerator.nextId(); // I don't need this, but the tournament server uses it...
|
||||||
|
|
||||||
private final User from;
|
private final NettyClient from;
|
||||||
private final User to;
|
private final NettyClient to;
|
||||||
private final String gameType;
|
private final String gameType;
|
||||||
private final SimpleTimer timer;
|
private final SimpleTimer timer;
|
||||||
|
|
||||||
private boolean isChallengeAccepted = false;
|
private boolean isChallengeAccepted = false;
|
||||||
|
|
||||||
public GameChallenge(User from, User to, String gameType, SimpleTimer timer) {
|
public GameChallenge(NettyClient from, NettyClient to, String gameType, SimpleTimer timer) {
|
||||||
this.from = from;
|
this.from = from;
|
||||||
this.to = to;
|
this.to = to;
|
||||||
this.gameType = gameType;
|
this.gameType = gameType;
|
||||||
@@ -23,8 +25,8 @@ public class GameChallenge {
|
|||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public User[] getUsers() {
|
public NettyClient[] getUsers() {
|
||||||
return new User[]{from, to};
|
return new NettyClient[]{from, to};
|
||||||
}
|
}
|
||||||
|
|
||||||
public void forceExpire() {
|
public void forceExpire() {
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
package org.toop.framework.networking.server;
|
package org.toop.framework.networking.server.challenges.gamechallenge;
|
||||||
|
|
||||||
|
import org.toop.framework.utils.SimpleTimer;
|
||||||
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package org.toop.framework.networking.server.client;
|
||||||
|
|
||||||
|
import org.toop.framework.networking.server.Game;
|
||||||
|
import org.toop.framework.utils.Pair;
|
||||||
|
|
||||||
|
public interface Client<G, P> {
|
||||||
|
long id();
|
||||||
|
|
||||||
|
String name();
|
||||||
|
void setName(String name);
|
||||||
|
|
||||||
|
Game game();
|
||||||
|
P player();
|
||||||
|
|
||||||
|
void addGame(Pair<G, P> gamePair);
|
||||||
|
void clearGame();
|
||||||
|
|
||||||
|
void send(String message);
|
||||||
|
}
|
||||||
@@ -1,16 +1,17 @@
|
|||||||
package org.toop.framework.networking.server;
|
package org.toop.framework.networking.server.client;
|
||||||
|
|
||||||
import io.netty.channel.ChannelHandlerContext;
|
import io.netty.channel.ChannelHandlerContext;
|
||||||
import org.toop.framework.game.players.ServerPlayer;
|
import org.toop.framework.game.players.ServerPlayer;
|
||||||
|
import org.toop.framework.networking.server.Game;
|
||||||
import org.toop.framework.utils.Pair;
|
import org.toop.framework.utils.Pair;
|
||||||
|
|
||||||
public class User implements ServerUser {
|
public class NettyClient implements Client<Game, ServerPlayer> {
|
||||||
final private long id;
|
final private long id;
|
||||||
|
private ChannelHandlerContext ctx;
|
||||||
private String name;
|
private String name;
|
||||||
private Pair<Game, ServerPlayer> gamePair;
|
private Pair<Game, ServerPlayer> gamePair;
|
||||||
private ChannelHandlerContext connectionContext;
|
|
||||||
|
|
||||||
public User(long userId, String name) {
|
public NettyClient(long userId, String name) {
|
||||||
this.id = userId;
|
this.id = userId;
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
@@ -33,7 +34,7 @@ public class User implements ServerUser {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void removeGame() {
|
public void clearGame() {
|
||||||
this.gamePair = null;
|
this.gamePair = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,7 +46,8 @@ public class User implements ServerUser {
|
|||||||
return this.gamePair.getLeft();
|
return this.gamePair.getLeft();
|
||||||
}
|
}
|
||||||
|
|
||||||
public ServerPlayer serverPlayer() {
|
@Override
|
||||||
|
public ServerPlayer player() {
|
||||||
return this.gamePair.getRight();
|
return this.gamePair.getRight();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,18 +57,12 @@ public class User implements ServerUser {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void sendMessage(String message) {
|
public void send(String message) {
|
||||||
IO.println(message);
|
IO.println(message);
|
||||||
ctx().channel().writeAndFlush(message);
|
ctx.channel().writeAndFlush(message + "\r\n");
|
||||||
}
|
|
||||||
|
|
||||||
public ChannelHandlerContext ctx() {
|
|
||||||
return connectionContext;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setCtx(ChannelHandlerContext ctx) {
|
public void setCtx(ChannelHandlerContext ctx) {
|
||||||
this.connectionContext = ctx;
|
this.ctx = ctx;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package org.toop.framework.networking.server.connectionHandler;
|
||||||
|
|
||||||
|
import org.toop.framework.networking.server.client.Client;
|
||||||
|
|
||||||
|
public interface ClientSession<G, P> {
|
||||||
|
Client<G, P> client();
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package org.toop.framework.networking.server.connectionHandler;
|
||||||
|
|
||||||
|
import io.netty.channel.ChannelHandlerContext;
|
||||||
|
import io.netty.channel.SimpleChannelInboundHandler;
|
||||||
|
import org.toop.framework.game.players.ServerPlayer;
|
||||||
|
import org.toop.framework.networking.server.Game;
|
||||||
|
import org.toop.framework.networking.server.client.NettyClient;
|
||||||
|
import org.toop.framework.networking.server.handlers.Handler;
|
||||||
|
import org.toop.framework.networking.server.parsing.ParsedMessage;
|
||||||
|
import org.toop.framework.networking.server.Server;
|
||||||
|
import org.toop.framework.networking.server.client.Client;
|
||||||
|
import org.toop.framework.networking.server.parsing.Parser;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
public class NettyClientSession extends SimpleChannelInboundHandler<String> implements ClientSession<Game, ServerPlayer> {
|
||||||
|
|
||||||
|
private final NettyClient client;
|
||||||
|
private final Server server;
|
||||||
|
private final Handler<ParsedMessage> handler;
|
||||||
|
|
||||||
|
public NettyClientSession(NettyClient client, Server server, Handler<ParsedMessage> handler) {
|
||||||
|
this.client = client;
|
||||||
|
this.server = server;
|
||||||
|
this.handler = handler;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Client<Game, ServerPlayer> client() {
|
||||||
|
return client;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void channelActive(ChannelHandlerContext ctx) {
|
||||||
|
ctx.writeAndFlush("Welcome " + client.id() + " please login" + "\n");
|
||||||
|
|
||||||
|
client.setCtx(ctx);
|
||||||
|
server.addUser(client); // TODO set correct name on login
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void channelRead0(ChannelHandlerContext ctx, String msg) {
|
||||||
|
|
||||||
|
IO.println(msg);
|
||||||
|
|
||||||
|
ParsedMessage p = Parser.parse(msg);
|
||||||
|
if (p == null) return;
|
||||||
|
|
||||||
|
IO.println(p.command() + " " + Arrays.toString(p.args()));
|
||||||
|
|
||||||
|
handler.handle(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
|
||||||
|
cause.printStackTrace();
|
||||||
|
ctx.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void channelInactive(ChannelHandlerContext ctx) {
|
||||||
|
server.removeUser(client);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package org.toop.framework.networking.server.gateway;
|
||||||
|
|
||||||
|
public interface GatewayServer {
|
||||||
|
void start() throws Exception;
|
||||||
|
void stop();
|
||||||
|
int port();
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package org.toop.framework.networking.server;
|
package org.toop.framework.networking.server.gateway;
|
||||||
|
|
||||||
import io.netty.bootstrap.ServerBootstrap;
|
import io.netty.bootstrap.ServerBootstrap;
|
||||||
import io.netty.channel.*;
|
import io.netty.channel.*;
|
||||||
@@ -13,11 +13,20 @@ import io.netty.handler.logging.LogLevel;
|
|||||||
import io.netty.handler.logging.LoggingHandler;
|
import io.netty.handler.logging.LoggingHandler;
|
||||||
import org.toop.framework.SnowflakeGenerator;
|
import org.toop.framework.SnowflakeGenerator;
|
||||||
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
|
import org.toop.framework.networking.server.client.NettyClient;
|
||||||
|
import org.toop.framework.networking.server.connectionHandler.NettyClientSession;
|
||||||
|
import org.toop.framework.networking.server.Server;
|
||||||
|
import org.toop.framework.networking.server.handlers.MessageHandler;
|
||||||
|
import org.toop.framework.networking.server.stores.NettyClientStore;
|
||||||
|
import org.toop.framework.networking.server.stores.TurnBasedGameStore;
|
||||||
|
import org.toop.framework.networking.server.stores.TurnBasedGameTypeStore;
|
||||||
|
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.CopyOnWriteArrayList;
|
||||||
|
|
||||||
public class MasterServer {
|
public class NettyGatewayServer implements GatewayServer {
|
||||||
private final int port;
|
private final int port;
|
||||||
private final Server gs;
|
private final Server gs;
|
||||||
|
|
||||||
@@ -25,11 +34,21 @@ public class MasterServer {
|
|||||||
EventLoopGroup bossGroup;
|
EventLoopGroup bossGroup;
|
||||||
EventLoopGroup workerGroup;
|
EventLoopGroup workerGroup;
|
||||||
|
|
||||||
public MasterServer(int port, Map<String, Class<? extends TurnBasedGame>> gameTypes, Duration challengeDuration) {
|
public NettyGatewayServer(
|
||||||
|
int port,
|
||||||
|
TurnBasedGameTypeStore turnBasedGameTypeStore,
|
||||||
|
Duration challengeDuration
|
||||||
|
) {
|
||||||
this.port = port;
|
this.port = port;
|
||||||
this.gs = new Server(gameTypes, challengeDuration);
|
this.gs = new Server(
|
||||||
|
challengeDuration,
|
||||||
|
turnBasedGameTypeStore,
|
||||||
|
new NettyClientStore(new ConcurrentHashMap<>()),
|
||||||
|
new TurnBasedGameStore(new CopyOnWriteArrayList<>())
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
public void start() throws InterruptedException {
|
public void start() throws InterruptedException {
|
||||||
|
|
||||||
bossGroup = new NioEventLoopGroup(1);
|
bossGroup = new NioEventLoopGroup(1);
|
||||||
@@ -54,8 +73,8 @@ public class MasterServer {
|
|||||||
pipeline.addLast(new StringEncoder());
|
pipeline.addLast(new StringEncoder());
|
||||||
|
|
||||||
long userid = SnowflakeGenerator.nextId();
|
long userid = SnowflakeGenerator.nextId();
|
||||||
User user = new User(userid, ""+userid);
|
NettyClient client = new NettyClient(userid, ""+userid);
|
||||||
pipeline.addLast(new ConnectionHandler(user, gs));
|
pipeline.addLast(new NettyClientSession(client, gs, new MessageHandler(gs, client)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
@@ -69,6 +88,7 @@ public class MasterServer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
public void stop() {
|
public void stop() {
|
||||||
if (future == null) {
|
if (future == null) {
|
||||||
return;
|
return;
|
||||||
@@ -82,4 +102,9 @@ public class MasterServer {
|
|||||||
bossGroup = null;
|
bossGroup = null;
|
||||||
workerGroup = null;
|
workerGroup = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int port() {
|
||||||
|
return port;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package org.toop.framework.networking.server.handlers;
|
||||||
|
|
||||||
|
public interface Handler<T> {
|
||||||
|
void handle(T message);
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package org.toop.framework.networking.server.handlers;
|
||||||
|
|
||||||
|
import org.toop.framework.game.players.ServerPlayer;
|
||||||
|
import org.toop.framework.networking.server.Game;
|
||||||
|
import org.toop.framework.networking.server.Server;
|
||||||
|
import org.toop.framework.networking.server.client.Client;
|
||||||
|
import org.toop.framework.networking.server.parsing.ParsedMessage;
|
||||||
|
import org.toop.framework.utils.Utils;
|
||||||
|
|
||||||
|
public class MessageHandler implements Handler<ParsedMessage> {
|
||||||
|
|
||||||
|
private final Server server;
|
||||||
|
private final Client<Game, ServerPlayer> client;
|
||||||
|
|
||||||
|
public MessageHandler(Server server, Client<Game, ServerPlayer> client) {
|
||||||
|
this.server = server;
|
||||||
|
this.client = client;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void handle(ParsedMessage message) {
|
||||||
|
switch (message.command()) {
|
||||||
|
case "ping" -> client.send("PONG");
|
||||||
|
case "login" -> handleLogin(message, client);
|
||||||
|
case "get" -> handleGet(message, client);
|
||||||
|
case "subscribe" -> handleSubscribe(message, client);
|
||||||
|
case "move" -> handleMove(message, client);
|
||||||
|
case "challenge" -> handleChallenge(message, client);
|
||||||
|
case "message" -> handleMessage(message, client);
|
||||||
|
case "help" -> handleHelp(message, client);
|
||||||
|
default -> client.send("ERROR Unknown command");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// DO NOT INVERT
|
||||||
|
private boolean hasArgs(String... args) {
|
||||||
|
return (args.length >= 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void handleLogin(ParsedMessage p, Client<Game, ServerPlayer> client) {
|
||||||
|
if (!hasArgs(p.args())) return;
|
||||||
|
|
||||||
|
client.setName(p.args()[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void handleSubscribe(ParsedMessage p, Client<Game, ServerPlayer> client) {
|
||||||
|
// TODO
|
||||||
|
}
|
||||||
|
|
||||||
|
private void handleHelp(ParsedMessage p, Client<Game, ServerPlayer> client) {
|
||||||
|
// TODO
|
||||||
|
}
|
||||||
|
|
||||||
|
private void handleMessage(ParsedMessage p, Client<Game, ServerPlayer> client) {
|
||||||
|
// TODO
|
||||||
|
}
|
||||||
|
|
||||||
|
private void handleGet(ParsedMessage p, Client<Game, ServerPlayer> client) {
|
||||||
|
if (!hasArgs(p.args())) return;
|
||||||
|
|
||||||
|
switch (p.args()[0]) {
|
||||||
|
case "playerlist" -> {
|
||||||
|
var names = server.onlineUsers().stream().map(Client::name).iterator();
|
||||||
|
client.send("SVR PLAYERLIST " + Utils.returnQuotedString(names));
|
||||||
|
}
|
||||||
|
case "gamelist" -> {
|
||||||
|
var names = server.gameTypes().stream().iterator();
|
||||||
|
client.send("SVR GAMELIST " + Utils.returnQuotedString(names));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void handleChallenge(ParsedMessage p, Client<Game, ServerPlayer> client) {
|
||||||
|
if (!hasArgs(p.args())) return;
|
||||||
|
if (p.args().length < 2) return;
|
||||||
|
|
||||||
|
if (p.args()[0].equalsIgnoreCase("accept")) {
|
||||||
|
try {
|
||||||
|
long id = Long.parseLong(p.args()[1]);
|
||||||
|
|
||||||
|
if (id <= 0) {
|
||||||
|
client.send("ERR id must be a positive number");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
server.acceptChallenge(id);
|
||||||
|
|
||||||
|
} catch (NumberFormatException e) {
|
||||||
|
client.send("ERR id is not a valid number or too big");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
server.challengeUser(client.name(), p.args()[0], p.args()[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void handleMove(ParsedMessage p, Client<Game, ServerPlayer> client) {
|
||||||
|
if(!hasArgs(p.args())) return;
|
||||||
|
|
||||||
|
// TODO check if not number
|
||||||
|
client.player().setMove(1L << Integer.parseInt(p.args()[0]));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package org.toop.framework.networking.server;
|
package org.toop.framework.networking.server.parsing;
|
||||||
|
|
||||||
public record ParsedMessage(String command, String... args) {}
|
public record ParsedMessage(String command, String... args) {}
|
||||||
|
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package org.toop.framework.networking.server.parsing;
|
||||||
|
|
||||||
|
import java.util.LinkedList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class Parser {
|
||||||
|
public static ParsedMessage parse(String msg) {
|
||||||
|
// TODO, what if empty string.
|
||||||
|
|
||||||
|
if (msg.isEmpty()) return null;
|
||||||
|
|
||||||
|
msg = msg.trim().toLowerCase();
|
||||||
|
|
||||||
|
List<String> parts = new LinkedList<>(List.of(msg.split(" ")));
|
||||||
|
|
||||||
|
if (parts.size() > 1) {
|
||||||
|
String command = parts.removeFirst();
|
||||||
|
return new ParsedMessage(command, parts.toArray(String[]::new));
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return new ParsedMessage(msg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package org.toop.framework.networking.server.stores;
|
||||||
|
|
||||||
|
import org.toop.framework.game.players.ServerPlayer;
|
||||||
|
import org.toop.framework.networking.server.Game;
|
||||||
|
import org.toop.framework.networking.server.client.Client;
|
||||||
|
|
||||||
|
public interface ClientStore<ID, T extends Client<Game, ServerPlayer>> extends Store<ID, T> {}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
package org.toop.framework.networking.server.stores;
|
||||||
|
|
||||||
|
public interface GameStore<T, K> extends Store<T, K> {}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package org.toop.framework.networking.server.stores;
|
||||||
|
|
||||||
|
import org.toop.framework.networking.server.client.NettyClient;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class NettyClientStore implements ClientStore<Long, NettyClient> {
|
||||||
|
final private Map<Long, NettyClient> users;
|
||||||
|
|
||||||
|
public NettyClientStore(Map<Long, NettyClient> usersMap) {
|
||||||
|
this.users = usersMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void add(NettyClient adding) {
|
||||||
|
users.putIfAbsent(adding.id(), adding);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void remove(Long remover) {
|
||||||
|
users.remove(remover);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public NettyClient get(Long getter) {
|
||||||
|
return users.get(getter);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Collection<NettyClient> all() {
|
||||||
|
return users.values();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package org.toop.framework.networking.server.stores;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
|
||||||
|
public interface Store<IDENTIFIER, STORED> {
|
||||||
|
void add(STORED adding);
|
||||||
|
void remove(IDENTIFIER remover);
|
||||||
|
STORED get(IDENTIFIER getter);
|
||||||
|
Collection<STORED> all();
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package org.toop.framework.networking.server.stores;
|
||||||
|
|
||||||
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
|
import org.toop.framework.networking.server.OnlineGame;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class TurnBasedGameStore implements GameStore<OnlineGame<TurnBasedGame>, OnlineGame<TurnBasedGame>> {
|
||||||
|
|
||||||
|
private List<OnlineGame<TurnBasedGame>> gameList;
|
||||||
|
|
||||||
|
public TurnBasedGameStore(List<OnlineGame<TurnBasedGame>> initGameList) {
|
||||||
|
this.gameList = initGameList;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void add(OnlineGame<TurnBasedGame> adding) {
|
||||||
|
gameList.addLast(adding);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void remove(OnlineGame<TurnBasedGame> remover) {
|
||||||
|
gameList.remove(remover);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public OnlineGame<TurnBasedGame> get(OnlineGame<TurnBasedGame> getter) {
|
||||||
|
return gameList.stream().filter(game->game.equals(getter)).findFirst().orElse(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Collection<OnlineGame<TurnBasedGame>> all() {
|
||||||
|
return gameList;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package org.toop.framework.networking.server.stores;
|
||||||
|
|
||||||
|
import org.toop.framework.gameFramework.model.game.TurnBasedGame;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
public class TurnBasedGameTypeStore {
|
||||||
|
|
||||||
|
private final Map<String, Supplier<? extends TurnBasedGame>> gameFactories = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
public TurnBasedGameTypeStore() {}
|
||||||
|
|
||||||
|
public void register(String key, Supplier<? extends TurnBasedGame> factory) {
|
||||||
|
gameFactories.put(key, factory);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void unregister(String key) {
|
||||||
|
gameFactories.remove(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
public TurnBasedGame create(String key) {
|
||||||
|
Supplier<? extends TurnBasedGame> factory = gameFactories.get(key);
|
||||||
|
if (factory == null) throw new IllegalArgumentException("Unknown game type: " + key);
|
||||||
|
return factory.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Supplier<? extends TurnBasedGame>> all() {
|
||||||
|
return Map.copyOf(gameFactories);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package org.toop.framework.networking.server;
|
package org.toop.framework.utils;
|
||||||
|
|
||||||
public interface SimpleTimer {
|
public interface SimpleTimer {
|
||||||
void forceExpire();
|
void forceExpire();
|
||||||
11
framework/src/main/java/org/toop/framework/utils/Utils.java
Normal file
11
framework/src/main/java/org/toop/framework/utils/Utils.java
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
package org.toop.framework.utils;
|
||||||
|
|
||||||
|
import org.apache.maven.surefire.shared.utils.StringUtils;
|
||||||
|
|
||||||
|
import java.util.Iterator;
|
||||||
|
|
||||||
|
public class Utils {
|
||||||
|
public static String returnQuotedString(Iterator<String> strings) { // TODO more places this could be useful
|
||||||
|
return "\"" + StringUtils.join(strings, "\",\"") + "\"";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -65,7 +65,7 @@
|
|||||||
//
|
//
|
||||||
// }
|
// }
|
||||||
//
|
//
|
||||||
// static class TestUser implements ServerUser {
|
// static class TestUser implements Client {
|
||||||
//
|
//
|
||||||
// final private long id;
|
// final private long id;
|
||||||
//
|
//
|
||||||
@@ -157,9 +157,9 @@
|
|||||||
//
|
//
|
||||||
// @Test
|
// @Test
|
||||||
// void testStartGame() {
|
// void testStartGame() {
|
||||||
// server.startGame("tictactoe", new User(0, "A"), new User(1, "B"));
|
// server.startGame("tictactoe", new NettyClient(0, "A"), new NettyClient(1, "B"));
|
||||||
// Assertions.assertEquals(1, server.ongoingGames().size());
|
// Assertions.assertEquals(1, server.ongoingGames().size());
|
||||||
// server.startGame("reversi", new User(0, "A"), new User(1, "B"));
|
// server.startGame("reversi", new NettyClient(0, "A"), new NettyClient(1, "B"));
|
||||||
// Assertions.assertEquals(2, server.ongoingGames().size());
|
// Assertions.assertEquals(2, server.ongoingGames().size());
|
||||||
// }
|
// }
|
||||||
//
|
//
|
||||||
|
|||||||
Reference in New Issue
Block a user