From 59dd27f1233cfd9bc342f2b9c502036e5677f7cc Mon Sep 17 00:00:00 2001 From: AleandroPagani Date: Sat, 25 Apr 2026 16:27:42 +0200 Subject: [PATCH 01/13] Add: JavaDOC explaining the network stack workflow --- .../it/polimi/ingsw/gc14/ServerLauncher.java | 33 +++++++++++++++---- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/src/main/java/it/polimi/ingsw/gc14/ServerLauncher.java b/src/main/java/it/polimi/ingsw/gc14/ServerLauncher.java index 67d4dfd..04de37c 100644 --- a/src/main/java/it/polimi/ingsw/gc14/ServerLauncher.java +++ b/src/main/java/it/polimi/ingsw/gc14/ServerLauncher.java @@ -13,12 +13,30 @@ import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class ServerLauncher { + /** + * Main server launcher that handles both TCP and RMI connections. + * The workflow is divided into two parts: game creation and game execution. + * + * The process flow for game creation is as follows: + * - The first client (TCP/RMI) requests to join the game by providing a username and the desired number of players + * - The TCP/RMI server checks {@link #playerList} and, if it is empty, sets the number of players according to the first user's request using {@link LimitedList#setLimit(int)} + * - The TCP/RMI server creates the {@link Game} with the requested number of players and adds the player to {@link #playerList} + * - Other players request to join the game (their requested number of players is ignored) + * - When the number of players in {@link #playerList} reaches the {@link LimitedList}'s limit, the list calls {@link #run()} + * - All players are notified with the {@link Game} + * + * The process flow for game execution is as follows: + * - The TCP/RMI server receives a {@link NetworkEvent} from a client and adds it to the {@link #actionQueue} + * - The {@link #run()} method repeatedly calls {@link #doFirstEvent()}, which takes the first event in the {@link #actionQueue} and tries to apply it + * - If the event is successfully applied to the model, all players receive the event + * - Otherwise, the player who sent the action receives an error notification + */ BlockingQueue actionQueue; GameController gameController; RMIServer serverRMI; TCPServer serverTCP; - static LimitedList players; + static LimitedList playerList; @@ -29,7 +47,7 @@ public class ServerLauncher { this.serverTCP = serverTCP; } - public boolean doFirstEven() throws InterruptedException, RemoteException { + public boolean doFirstEvent() throws InterruptedException, RemoteException { NetworkEvent event = actionQueue.take(); if(event.apply(gameController)) { serverRMI.notifyAll(event); @@ -49,14 +67,14 @@ public class ServerLauncher { // Il server RMI e il server TCP quando ricevono un doEvent devono aggiungere l'evento alla coda condivisa // Questa classe esegue gli eventi nella coda e chiama il notify all e notify error sia RMI che TCP - players = new LimitedList<>(5, ()->{}); + playerList = new LimitedList<>(5, ()->{}); BlockingQueue actionQueue = new LinkedBlockingQueue<>(); GameController gameController = new GameController(); - RMIServer serverRMI = new RMIServer(gameController, 1099, actionQueue, players); - TCPServer serverTCP = new TCPServer(gameController, 8080, actionQueue, players); + RMIServer serverRMI = new RMIServer(gameController, 1099, actionQueue, playerList); + TCPServer serverTCP = new TCPServer(gameController, 8080, actionQueue, playerList); ServerLauncher launcher = new ServerLauncher(actionQueue, gameController, serverRMI, serverTCP); - players.setAction(()->{ + playerList.setAction(()->{ try { launcher.run(); } catch (InterruptedException e) { @@ -76,9 +94,10 @@ public class ServerLauncher { serverTCP.broadcastModel(gameController.getModel()); + // Game execution while (true) { try { - this.doFirstEven(); + this.doFirstEvent(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; From 3a8706603c6d2cf592ada1c1a39c2eb4664db520 Mon Sep 17 00:00:00 2001 From: AleandroPagani Date: Sat, 25 Apr 2026 17:34:28 +0200 Subject: [PATCH 02/13] Add: JavaDOC in ServerLauncher Fix: Action error handling in the entire network stack Modified: TCP's broadcast methods name --- .../ingsw/gc14/Network/NetworkEvent.java | 17 +++- .../RMI/Client/ClientCallbackImpl.java | 14 ++- .../Network/RMI/Common/IClientCallback.java | 1 - .../gc14/Network/RMI/Server/RMIServer.java | 4 - .../gc14/Network/TCP/Client/TCPClient.java | 17 +++- .../Network/TCP/Server/ClientHandler.java | 6 +- .../gc14/Network/TCP/Server/TCPServer.java | 4 +- .../it/polimi/ingsw/gc14/ServerLauncher.java | 89 ++++++++++++------- 8 files changed, 100 insertions(+), 52 deletions(-) diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvent.java b/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvent.java index abc510c..1a5d50c 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvent.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvent.java @@ -1,7 +1,6 @@ package it.polimi.ingsw.gc14.Network; import it.polimi.ingsw.gc14.Controller.GameController; -import javafx.event.Event; import java.io.Serializable; @@ -12,9 +11,23 @@ public abstract class NetworkEvent implements Serializable { } protected EventType eventType; public EventType getEventType() {return eventType;} - protected NetworkEvent(String username, EventType eventType) { + protected boolean isError; + public boolean getIsError() {return isError;} + public void setIsError(boolean isError) {this.isError = isError;} + + protected NetworkEvent(String username, EventType eventType, boolean isError) { this.username = username; this.eventType = eventType; + this.isError = isError; + } + + @Override + public String toString() { + if(isError) { + return ("ERROR: action " + eventType.toString()); + } else { + return ("ACTION: action " + eventType.toString()); + } } public abstract boolean apply(GameController gameController); diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Client/ClientCallbackImpl.java b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Client/ClientCallbackImpl.java index d6b54d7..871b653 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Client/ClientCallbackImpl.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Client/ClientCallbackImpl.java @@ -23,13 +23,11 @@ public class ClientCallbackImpl extends UnicastRemoteObject implements IClientCa @Override public void onAction(NetworkEvent event) throws RemoteException { - event.apply(clientController.localController); // delega tutto al controller - //clientController.view.update(); TODO + if(event.getIsError()) { + System.out.println(event.toString()); + } else { + event.apply(clientController.localController); // delega tutto al controller + //clientController.view.update(); TODO + } } - - @Override - public void onError(String message) throws RemoteException { - clientController.onError(message); - } - } diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Common/IClientCallback.java b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Common/IClientCallback.java index 5ff2b0b..0292fcc 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Common/IClientCallback.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Common/IClientCallback.java @@ -8,5 +8,4 @@ import java.rmi.*; public interface IClientCallback extends Remote { void onGameInit(Game model) throws RemoteException; void onAction(NetworkEvent action) throws RemoteException; - void onError(String message) throws RemoteException; } \ No newline at end of file diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Server/RMIServer.java b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Server/RMIServer.java index fc74f3c..e575a8f 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Server/RMIServer.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Server/RMIServer.java @@ -83,10 +83,6 @@ public class RMIServer implements IGameServer { cb.onGameInit(model); } } - public void notifyError(String username, String message) throws RemoteException { - IClientCallback cb = clients.get(username); - if (cb != null) cb.onError(message); - } diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Client/TCPClient.java b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Client/TCPClient.java index d29de4b..9a39808 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Client/TCPClient.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Client/TCPClient.java @@ -1,6 +1,7 @@ package it.polimi.ingsw.gc14.Network.TCP.Client; import it.polimi.ingsw.gc14.Controller.GameController; +import it.polimi.ingsw.gc14.Model.Game; import it.polimi.ingsw.gc14.Network.NetworkEvent; import it.polimi.ingsw.gc14.Network.NetworkEvents.AddPlayer; @@ -46,7 +47,21 @@ public class TCPClient implements Serializable{ private void ReceiveMessage(){ while(true){ try{ - ((NetworkEvent)(socketReceive.readObject())).apply(controller); + Object read = socketReceive.readObject(); + + if (read instanceof NetworkEvent) { //TODO non fare con instanceof + NetworkEvent event = (NetworkEvent) read; + if(event.getIsError()) { + System.out.println(event.toString()); + } else { + event.apply(controller); + //clientController.view.update(); TODO + } + } + else if (read instanceof Game) { + controller.setModel((Game) read); + } + } catch(IOException e){ e.printStackTrace(); diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/ClientHandler.java b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/ClientHandler.java index d471ab0..a989868 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/ClientHandler.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/ClientHandler.java @@ -43,8 +43,8 @@ public class ClientHandler implements Runnable { while(true){ try{ input = (NetworkEvent) (in.readObject()); - if(actionQueue.add(input)){ - server.broadcastUpdate(input); + if(!actionQueue.add(input)){ + System.out.println("An error occurred in inserting an action into queue"); } } catch(java.io.IOException e){ @@ -53,8 +53,6 @@ public class ClientHandler implements Runnable { catch (ClassNotFoundException e){ throw new RuntimeException(e); } - - } } catch (IOException e) { diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/TCPServer.java b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/TCPServer.java index 7c928c3..2a79695 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/TCPServer.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/TCPServer.java @@ -118,11 +118,11 @@ public class TCPServer { this.playerList = players; } - public void broadcastUpdate(NetworkEvent event){ + public void notifAll(NetworkEvent event){ clientHandlers.forEach((x) -> x.notifyEvent(event)); } - public void broadcastModel(Game model){ + public void notifyAll(Game model){ clientHandlers.forEach((x) -> x.notifyModel(model)); } } diff --git a/src/main/java/it/polimi/ingsw/gc14/ServerLauncher.java b/src/main/java/it/polimi/ingsw/gc14/ServerLauncher.java index 04de37c..dabe7a0 100644 --- a/src/main/java/it/polimi/ingsw/gc14/ServerLauncher.java +++ b/src/main/java/it/polimi/ingsw/gc14/ServerLauncher.java @@ -12,34 +12,58 @@ import java.rmi.RemoteException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; -public class ServerLauncher { - /** - * Main server launcher that handles both TCP and RMI connections. - * The workflow is divided into two parts: game creation and game execution. - * - * The process flow for game creation is as follows: - * - The first client (TCP/RMI) requests to join the game by providing a username and the desired number of players - * - The TCP/RMI server checks {@link #playerList} and, if it is empty, sets the number of players according to the first user's request using {@link LimitedList#setLimit(int)} - * - The TCP/RMI server creates the {@link Game} with the requested number of players and adds the player to {@link #playerList} - * - Other players request to join the game (their requested number of players is ignored) - * - When the number of players in {@link #playerList} reaches the {@link LimitedList}'s limit, the list calls {@link #run()} - * - All players are notified with the {@link Game} - * - * The process flow for game execution is as follows: - * - The TCP/RMI server receives a {@link NetworkEvent} from a client and adds it to the {@link #actionQueue} - * - The {@link #run()} method repeatedly calls {@link #doFirstEvent()}, which takes the first event in the {@link #actionQueue} and tries to apply it - * - If the event is successfully applied to the model, all players receive the event - * - Otherwise, the player who sent the action receives an error notification - */ +/** + * Main server launcher that handles both TCP and RMI connections. + * The workflow is divided into two parts: game creation and game execution. + * + * The process flow for game creation is as follows: + * - The first client (TCP/RMI) requests to join the game by providing a username and the desired number of players + * - The TCP/RMI server checks {@link #playerList} and, if it is empty, sets the number of players according to the first user's request using {@link LimitedList#setLimit(int)} + * - The TCP/RMI server creates the {@link Game} with the requested number of players and adds the player to {@link #playerList} + * - Other players request to join the game (their requested number of players is ignored) + * - When the number of players in {@link #playerList} reaches the {@link LimitedList}'s limit, the list calls {@link #run()} + * - All players are notified with the {@link Game} + * + * The process flow for game execution is as follows: + * - The TCP/RMI server receives a {@link NetworkEvent} from a client and adds it to the {@link #actionQueue} + * - The {@link #run()} method repeatedly calls {@link #doFirstEvent()}, which takes the first event in the {@link #actionQueue} and tries to apply it + * - If the event is successfully applied to the model, all players receive the event + * - Otherwise, the player who sent the action receives an error notification + */ +public class ServerLauncher { + + /** + * List containing the events that have to be applied to the game's model. + * Thread safe by design. + */ BlockingQueue actionQueue; + + /** Game controller. Used to apply events */ GameController gameController; + + /** Server RMI. Handles RMI clients */ RMIServer serverRMI; + + /** Server TCP. Handles TCP clients */ TCPServer serverTCP; + + /** + * List containing the username of joined players. + * {@link LimitedList}'s limit defines at which size the list calls its action + * Both limit and action can be set with {@link LimitedList#setLimit(int)} and {@link LimitedList#setAction(Runnable)} + * The limit is set by the first player joining the game. The action consists in calling {@link #run()} + */ static LimitedList playerList; - + /** + * Class constructor that initializes the attributes. + * @param actionQueue is the list containing the events + * @param gameController is the game controller + * @param serverRMI is the server RMI + * @param serverTCP is the server TCP + */ public ServerLauncher(BlockingQueue actionQueue, GameController gameController, RMIServer serverRMI, TCPServer serverTCP) { this.actionQueue = actionQueue; this.serverRMI = serverRMI; @@ -47,17 +71,22 @@ public class ServerLauncher { this.serverTCP = serverTCP; } + + /** + * Takes the first event in the actionQueue and attempt to apply it to the game controller. + * If the event can be applied, all clients (both TCP and RMI) are notified with the event. Otherwise, the user who sent the action will be notified with an error. + * @return the outcome of attempting to apply the event to the controller + * @throws InterruptedException if any problem in accessing actionQueue is issued + * @throws RemoteException if any RMI problem is issued + */ public boolean doFirstEvent() throws InterruptedException, RemoteException { NetworkEvent event = actionQueue.take(); - if(event.apply(gameController)) { - serverRMI.notifyAll(event); - serverTCP.broadcastUpdate(event); - return true; - } else { - serverRMI.notifyError(event.getUsername(), "Mossa non valida"); // TODO Converrebbe mettere in network event un booleano che dice se รจ stato accettato e fare una notifyAll anche per errori - //serverTCP // TODO non esiste un notify error (guarda sopra) - return false; - } + event.setIsError(!event.apply(gameController)); + + serverRMI.notifyAll(event); + serverTCP.notifAll(event); + + return !event.getIsError(); } @@ -91,7 +120,7 @@ public class ServerLauncher { public void run() throws InterruptedException, RemoteException { serverRMI.notifyAll(gameController.getModel()); - serverTCP.broadcastModel(gameController.getModel()); + serverTCP.notifyAll(gameController.getModel()); // Game execution From 27903f1738756cd6f911ff2907a09b32bd90e476 Mon Sep 17 00:00:00 2001 From: AleandroPagani Date: Sat, 25 Apr 2026 17:36:24 +0200 Subject: [PATCH 03/13] Fix: compilation errors due to wrong number of parameters --- .../it/polimi/ingsw/gc14/Network/NetworkEvents/AddPlayer.java | 2 +- .../ingsw/gc14/Network/NetworkEvents/DrawLowerBuildingCard.java | 2 +- .../ingsw/gc14/Network/NetworkEvents/DrawLowerTribeCard.java | 2 +- .../ingsw/gc14/Network/NetworkEvents/DrawUpperBuildingCard.java | 2 +- .../ingsw/gc14/Network/NetworkEvents/DrawUpperTribeCard.java | 2 +- .../gc14/Network/NetworkEvents/PickOptionalBuildingCard.java | 2 +- .../ingsw/gc14/Network/NetworkEvents/PickOptionalTribeCard.java | 2 +- .../it/polimi/ingsw/gc14/Network/NetworkEvents/SlotChoice.java | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/AddPlayer.java b/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/AddPlayer.java index d8ab797..8466942 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/AddPlayer.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/AddPlayer.java @@ -13,7 +13,7 @@ public class AddPlayer extends NetworkEvent implements Serializable { return proposedNPlayer; } public AddPlayer(String username, int proposedNPlayer) { - super(username, EventType.ADD_PLAYER); + super(username, EventType.ADD_PLAYER, false); this.proposedNPlayer = proposedNPlayer; } @Override diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/DrawLowerBuildingCard.java b/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/DrawLowerBuildingCard.java index 2456a6a..5656ac8 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/DrawLowerBuildingCard.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/DrawLowerBuildingCard.java @@ -11,7 +11,7 @@ public class DrawLowerBuildingCard extends NetworkEvent implements Serializable private int pos; public DrawLowerBuildingCard(String username, int pos){ - super(username, EventType.DRAW_LOWER_BUILD); + super(username, EventType.DRAW_LOWER_BUILD, false); this.pos = pos; } diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/DrawLowerTribeCard.java b/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/DrawLowerTribeCard.java index 64b0a17..277627a 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/DrawLowerTribeCard.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/DrawLowerTribeCard.java @@ -11,7 +11,7 @@ public class DrawLowerTribeCard extends NetworkEvent implements Serializable{ private int pos; public DrawLowerTribeCard(String username, int pos){ - super(username, EventType.DRAW_LOWER_TRIBE); + super(username, EventType.DRAW_LOWER_TRIBE, false); this.pos = pos; } diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/DrawUpperBuildingCard.java b/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/DrawUpperBuildingCard.java index 5f0a985..6fb06cf 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/DrawUpperBuildingCard.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/DrawUpperBuildingCard.java @@ -11,7 +11,7 @@ public class DrawUpperBuildingCard extends NetworkEvent implements Serializable private int pos; public DrawUpperBuildingCard(String username, int pos){ - super(username, EventType.DRAW_UPPER_BUILD); + super(username, EventType.DRAW_UPPER_BUILD, false); this.pos = pos; } diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/DrawUpperTribeCard.java b/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/DrawUpperTribeCard.java index 69ab281..8d37f02 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/DrawUpperTribeCard.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/DrawUpperTribeCard.java @@ -11,7 +11,7 @@ public class DrawUpperTribeCard extends NetworkEvent implements Serializable{ private int pos; public DrawUpperTribeCard(String username, int pos){ - super(username, EventType.DRAW_UPPER_TRIBE); + super(username, EventType.DRAW_UPPER_TRIBE, false); this.pos = pos; } diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/PickOptionalBuildingCard.java b/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/PickOptionalBuildingCard.java index a1fde73..36be45c 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/PickOptionalBuildingCard.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/PickOptionalBuildingCard.java @@ -11,7 +11,7 @@ public class PickOptionalBuildingCard extends NetworkEvent implements Serializa private int pos; public PickOptionalBuildingCard(String username, int pos){ - super(username, EventType.PICK_OPTIONAL_BUILD); + super(username, EventType.PICK_OPTIONAL_BUILD, false); this.pos = pos; } diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/PickOptionalTribeCard.java b/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/PickOptionalTribeCard.java index d739e3c..f2dadac 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/PickOptionalTribeCard.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/PickOptionalTribeCard.java @@ -11,7 +11,7 @@ public class PickOptionalTribeCard extends NetworkEvent implements Serializable private int pos; public PickOptionalTribeCard(String username, int pos){ - super(username, EventType.PICK_OPTIONAL_TRIBE); + super(username, EventType.PICK_OPTIONAL_TRIBE, false); this.pos = pos; } diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/SlotChoice.java b/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/SlotChoice.java index 97000d9..4bf0d12 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/SlotChoice.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/NetworkEvents/SlotChoice.java @@ -11,7 +11,7 @@ public class SlotChoice extends NetworkEvent implements Serializable { private int pos; public SlotChoice(String username, int pos) { - super(username, EventType.SLOT_CHOICE); + super(username, EventType.SLOT_CHOICE, false); this.pos = pos; } From 6ebfd4d0260780548f597d7c82a15d0e690a6388 Mon Sep 17 00:00:00 2001 From: AleandroPagani Date: Sat, 25 Apr 2026 18:16:13 +0200 Subject: [PATCH 04/13] Add: complete JavaDOC to ServerLauncher --- .../gc14/Network/RMI/Server/RMIServer.java | 2 +- .../gc14/Network/TCP/Server/TCPServer.java | 2 +- .../it/polimi/ingsw/gc14/ServerLauncher.java | 60 +++++++++++-------- 3 files changed, 38 insertions(+), 26 deletions(-) diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Server/RMIServer.java b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Server/RMIServer.java index e575a8f..1770da4 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Server/RMIServer.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Server/RMIServer.java @@ -52,7 +52,7 @@ public class RMIServer implements IGameServer { if (controller.addPlayer(username)) { if(playerList.size()==0) { - Game game= new Game(preferredInt); + Game game = new Game(preferredInt); controller.setModel(game); playerList.setLimit(preferredInt); } diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/TCPServer.java b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/TCPServer.java index 2a79695..fc86f84 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/TCPServer.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/TCPServer.java @@ -118,7 +118,7 @@ public class TCPServer { this.playerList = players; } - public void notifAll(NetworkEvent event){ + public void notifyAll(NetworkEvent event){ clientHandlers.forEach((x) -> x.notifyEvent(event)); } diff --git a/src/main/java/it/polimi/ingsw/gc14/ServerLauncher.java b/src/main/java/it/polimi/ingsw/gc14/ServerLauncher.java index dabe7a0..df3c776 100644 --- a/src/main/java/it/polimi/ingsw/gc14/ServerLauncher.java +++ b/src/main/java/it/polimi/ingsw/gc14/ServerLauncher.java @@ -23,18 +23,18 @@ import java.util.concurrent.LinkedBlockingQueue; * - The TCP/RMI server creates the {@link Game} with the requested number of players and adds the player to {@link #playerList} * - Other players request to join the game (their requested number of players is ignored) * - When the number of players in {@link #playerList} reaches the {@link LimitedList}'s limit, the list calls {@link #run()} - * - All players are notified with the {@link Game} + * - All players are notified of the {@link Game} * * The process flow for game execution is as follows: * - The TCP/RMI server receives a {@link NetworkEvent} from a client and adds it to the {@link #actionQueue} * - The {@link #run()} method repeatedly calls {@link #doFirstEvent()}, which takes the first event in the {@link #actionQueue} and tries to apply it - * - If the event is successfully applied to the model, all players receive the event - * - Otherwise, the player who sent the action receives an error notification + * - If the event cannot be successfully applied to the model, its {@code isError} flag is set to {@code true} + * - All players are notified of the event */ public class ServerLauncher { /** - * List containing the events that have to be applied to the game's model. + * Queue containing the events to be applied to the game model. * Thread safe by design. */ BlockingQueue actionQueue; @@ -49,9 +49,9 @@ public class ServerLauncher { TCPServer serverTCP; /** - * List containing the username of joined players. + * List containing the usernames of joined players. * {@link LimitedList}'s limit defines at which size the list calls its action - * Both limit and action can be set with {@link LimitedList#setLimit(int)} and {@link LimitedList#setAction(Runnable)} + * Both the limit and the action can be set using {@link LimitedList#setLimit(int)} and {@link LimitedList#setAction(Runnable)} * The limit is set by the first player joining the game. The action consists in calling {@link #run()} */ static LimitedList playerList; @@ -59,10 +59,10 @@ public class ServerLauncher { /** * Class constructor that initializes the attributes. - * @param actionQueue is the list containing the events - * @param gameController is the game controller - * @param serverRMI is the server RMI - * @param serverTCP is the server TCP + * @param actionQueue The queue containing the events + * @param gameController The game controller + * @param serverRMI The server RMI + * @param serverTCP The server TCP */ public ServerLauncher(BlockingQueue actionQueue, GameController gameController, RMIServer serverRMI, TCPServer serverTCP) { this.actionQueue = actionQueue; @@ -73,29 +73,34 @@ public class ServerLauncher { /** - * Takes the first event in the actionQueue and attempt to apply it to the game controller. - * If the event can be applied, all clients (both TCP and RMI) are notified with the event. Otherwise, the user who sent the action will be notified with an error. - * @return the outcome of attempting to apply the event to the controller - * @throws InterruptedException if any problem in accessing actionQueue is issued - * @throws RemoteException if any RMI problem is issued + * Takes the first event in the actionQueue and attempts to apply it to the game controller. + * If the event cannot be applied, its isError flag is set to true; otherwise, it is set to false. + * All clients (both TCP and RMI) are notified of the event + * @return the outcome of applying the event to the controller + * @throws InterruptedException if an error occurs while accessing the actionQueue + * @throws RemoteException if an RMI error occurs */ public boolean doFirstEvent() throws InterruptedException, RemoteException { NetworkEvent event = actionQueue.take(); event.setIsError(!event.apply(gameController)); serverRMI.notifyAll(event); - serverTCP.notifAll(event); + serverTCP.notifyAll(event); return !event.getIsError(); } - public static void main() throws RemoteException, InterruptedException { - // TODO - // Deve avere una coda con gli eventi. - // Il server RMI e il server TCP quando ricevono un doEvent devono aggiungere l'evento alla coda condivisa - // Questa classe esegue gli eventi nella coda e chiama il notify all e notify error sia RMI che TCP - + /** + * The first method executed when the server program is launched. + * It creates all the objects needed: playerList, actionQueue, gameController, serverRMI, serverTCP, launcher. + * Then sets the playerList's action to execute launcher.run() and starts the TCP/RMI servers. + * Note: the model is initialized and set in the controller in TCP/RMI servers when the first user decides the number of players. + * + * @throws InterruptedException if this exception is issued by run method + * @throws RemoteException if this exception is issued by run method + */ + public static void main(String[] args) throws InterruptedException, RemoteException { playerList = new LimitedList<>(5, ()->{}); BlockingQueue actionQueue = new LinkedBlockingQueue<>(); GameController gameController = new GameController(); @@ -117,12 +122,19 @@ public class ServerLauncher { new Thread(()->{serverTCP.start();}).start(); } - public void run() throws InterruptedException, RemoteException { + /** + * Creates and executes the game. + * Game creation: TCP/RMI servers send the game model to all players. + * Game execution: repeatedly calls doFirstEvent() to process the events in the actionQueue. + * @throws InterruptedException if the TCP server thread is interrupted + * @throws RemoteException if an RMI error occurs + */ + public void run() throws InterruptedException, RemoteException { + // Game creation serverRMI.notifyAll(gameController.getModel()); serverTCP.notifyAll(gameController.getModel()); - // Game execution while (true) { try { From 269ce0d13bf1419267a46d908df5c892e2461e1e Mon Sep 17 00:00:00 2001 From: AleandroPagani Date: Sat, 25 Apr 2026 18:55:28 +0200 Subject: [PATCH 05/13] Add: partial JavaDOC to RMIServer --- .../gc14/Network/RMI/Server/RMIServer.java | 75 ++++++++++++------- 1 file changed, 50 insertions(+), 25 deletions(-) diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Server/RMIServer.java b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Server/RMIServer.java index 1770da4..d960cc1 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Server/RMIServer.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Server/RMIServer.java @@ -15,19 +15,47 @@ import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; - import java.rmi.*; + +/** + * Server RMI. Exposes a method to join the game and one to execute an event. + */ public class RMIServer implements IGameServer { + /** Server game's controller */ private GameController controller; + + /** Server game's model */ + private Game model; + + /** RMI registry */ private Registry registry; + + /** RMI port */ private int nPort; + + /** Map containing the associations between a player's username and its callback */ private final Map clients = new ConcurrentHashMap<>(); + + /** Queue containing the events to be applied to the game model */ BlockingQueue actionQueue; + + /** + * List containing the usernames of joined players. + * {@link LimitedList}'s limit defines at which size the list calls its action. The limit can be set using {@link LimitedList#setLimit(int)}. + */ private LimitedList playerList; - // Costruttore + + /** + * Class constructor that initializes the attributes. + * @param controller The game controller + * @param nPort The RMI port + * @param actionQueue The action queue + * @param playerList The player's usernames list + * @throws RemoteException if an RMI error occurs + */ public RMIServer(GameController controller, int nPort, BlockingQueue actionQueue,LimitedList playerList) throws RemoteException { this.controller = controller; this.nPort = nPort; @@ -36,26 +64,29 @@ public class RMIServer implements IGameServer { } - - - - - // Metodi esposti RMI - public void setController (GameController controller) { - this.controller = controller; - } + // RMI's exposed methods + /** + * Allows a player to join the game. + * If the desired number of player is invalid, the request is rejected. + * If this is the first player, a new game model is created and passed to the controller. Additionally, the playerList's limit is set. + * Then, if the controller successfully adds the player, the username is added to {@link #playerList} and {@link #clients}. + * @param username The player's name + * @param preferredInt The desired number of players + * @param callback The client's callback interface + * @return true if the player successfully joined the game, false otherwise + */ @Override - public boolean joinGame(String username, int preferredInt,IClientCallback callback) { + public boolean joinGame(String username, int preferredInt, IClientCallback callback) { + if (preferredInt<2 || preferredInt>5) { + return false; + } synchronized (controller) { - if(playerList.size()==0 && (preferredInt<2||preferredInt>5)) - return false; + if(playerList.isEmpty()){ + model = new Game(preferredInt); + controller.setModel(model); + playerList.setLimit(preferredInt); + } if (controller.addPlayer(username)) { - if(playerList.size()==0) - { - Game game = new Game(preferredInt); - controller.setModel(game); - playerList.setLimit(preferredInt); - } playerList.add(username); clients.put(username, callback); return true; @@ -69,9 +100,6 @@ public class RMIServer implements IGameServer { } - - - // Metodi interni del server public void notifyAll(NetworkEvent action) throws RemoteException { for (IClientCallback cb : clients.values()) { @@ -85,9 +113,6 @@ public class RMIServer implements IGameServer { } - - - // Metodi per avviare server RMI public boolean start() { try { From 3f727335a9c4e28d2131ce7c647ab1634e959cd9 Mon Sep 17 00:00:00 2001 From: AleandroPagani Date: Sat, 25 Apr 2026 19:11:33 +0200 Subject: [PATCH 06/13] Add: Complete JavaDOC to RMIServer --- .../gc14/Network/RMI/Server/RMIServer.java | 38 +++++++++++++++++-- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Server/RMIServer.java b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Server/RMIServer.java index d960cc1..3578350 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Server/RMIServer.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Server/RMIServer.java @@ -64,6 +64,7 @@ public class RMIServer implements IGameServer { } + // RMI's exposed methods /** * Allows a player to join the game. @@ -94,18 +95,36 @@ public class RMIServer implements IGameServer { return false; } } + + + /** + * Push an action in actionQueue. + * @param action The desired actio + * @return true if the action was successfully added, false otherwise + */ @Override - public boolean doEvent(NetworkEvent event) throws RemoteException { - return actionQueue.offer(event); + public boolean doEvent(NetworkEvent action) { + return actionQueue.offer(action); } - // Metodi interni del server + + // RMI's internal methods + /** + * Sends an action to all RMI clients. + * @param action The desired action + */ public void notifyAll(NetworkEvent action) throws RemoteException { for (IClientCallback cb : clients.values()) { cb.onAction(action); } } + + + /** + * Sends a model game to all RMI clients. + * @param model The desired model + */ public void notifyAll(Game model) throws RemoteException { for (IClientCallback cb : clients.values()) { cb.onGameInit(model); @@ -113,12 +132,17 @@ public class RMIServer implements IGameServer { } + // Metodi per avviare server RMI + /** + * Starts the RMI server. + * @return true if the server starts successfully, false otherwise + */ public boolean start() { try { registry = LocateRegistry.createRegistry(nPort); registry.rebind("RMIGameServer", this); - System.out.println("RMI Server avviato sulla porta "+nPort); + System.out.println("RMI Server started on port: "+nPort); return true; } catch (Exception e) { @@ -126,6 +150,12 @@ public class RMIServer implements IGameServer { return false; } } + + + /** + * Stops the RMI server. + * @return true if the server stops successfully, false otherwise + */ public boolean stop() { try { registry.unbind("RMIGameServer"); From 2f6a20b9f8a7d458a445a068ebbe9f245c88158b Mon Sep 17 00:00:00 2001 From: AleandroPagani Date: Sat, 25 Apr 2026 19:23:26 +0200 Subject: [PATCH 07/13] Add: Complete JavaDOC of RMIClient and ClientCallbackImpl --- .../RMI/Client/ClientCallbackImpl.java | 31 ++++++++++- .../gc14/Network/RMI/Client/RMIClient.java | 53 ++++++++++++------- 2 files changed, 64 insertions(+), 20 deletions(-) diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Client/ClientCallbackImpl.java b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Client/ClientCallbackImpl.java index 871b653..928fa52 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Client/ClientCallbackImpl.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Client/ClientCallbackImpl.java @@ -8,25 +8,52 @@ import it.polimi.ingsw.gc14.Network.RMI.Common.IClientCallback; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; + +/** + * RMI client callback implementation of {@link IClientCallback}. + * Receives notifications from the server and updates the client game model. + */ public class ClientCallbackImpl extends UnicastRemoteObject implements IClientCallback { + /** The client controller used to apply events and update the model */ private final ClientController clientController; + + /** + * Class constructor. + * @param clientController the client controller + * @throws RemoteException if any RMI error occurs + */ public ClientCallbackImpl(ClientController clientController) throws RemoteException { this.clientController = clientController; } + + /** + * Called by the server when the game is initialized. + * Sets the client game model in the {@link ClientController}. + * @param model the initialized {@link Game} model + * @throws RemoteException if any RMI error occurs + */ @Override public void onGameInit(Game model) throws RemoteException { - clientController.setModel(model); // setta il model + clientController.setModel(model); } + + /** + * Called by the server when an action has been accepted. + * If the event contains an error, it is printed to the console. + * Otherwise, the event is applied to the local model. + * @param event the {@link NetworkEvent} sent by the server + * @throws RemoteException if any RMI error occurs + */ @Override public void onAction(NetworkEvent event) throws RemoteException { if(event.getIsError()) { System.out.println(event.toString()); } else { - event.apply(clientController.localController); // delega tutto al controller + event.apply(clientController.localController); //clientController.view.update(); TODO } } diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Client/RMIClient.java b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Client/RMIClient.java index 8d0721c..84d797f 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Client/RMIClient.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Client/RMIClient.java @@ -1,43 +1,56 @@ package it.polimi.ingsw.gc14.Network.RMI.Client; +import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import it.polimi.ingsw.gc14.Controller.ClientController; import it.polimi.ingsw.gc14.Network.NetworkEvent; +import it.polimi.ingsw.gc14.Network.RMI.Common.IClientCallback; import it.polimi.ingsw.gc14.Network.RMI.Common.IGameServer; +import it.polimi.ingsw.gc14.Network.RMI.Server.RMIServer; -public class RMIClient { +/** + * Client RMI. Uses the methods exposed by the server RMI. + */ +public class RMIClient { + /** The host address of the RMI server */ private final String host; + + /** The port of the RMI server */ private final int port; + + /** The remote stub used to call methods on the server */ private IGameServer stub; + + /** + * Class constructor. + * @param host the host address of the RMI server + * @param port the port of the RMI server + */ public RMIClient(String host, int port) { this.host = host; this.port = port; } - public boolean connect(String username,int preferredInt,ClientController clientController) { - // 1. Connettiti al registry + /** + * Connects to the RMI server and attempts to join the game. + * Looks up the RMI registry to retrieve the {@link IGameServer} stub. + * Then, creates a {@link ClientCallbackImpl} and calls {@link RMIServer#joinGame(String, int, IClientCallback)}. + * @param username the player's username + * @param preferredInt the desired number of players + * @param clientController the client controller used to create the callback + * @return true if the player successfully joined the game, false otherwise + */ + public boolean connect(String username,int preferredInt, ClientController clientController) { try { Registry registry = LocateRegistry.getRegistry(host, port); - - // 2. Prendi lo stub del server this.stub = (IGameServer) registry.lookup("RMIGameServer"); - - // 3. Crea il callback e registralo ClientCallbackImpl callback = new ClientCallbackImpl(clientController); - if (!stub.joinGame(username,preferredInt, callback)) - { - stub = null; - return false; - } - else - { - return true; - } + return stub.joinGame(username, preferredInt, callback); } catch (Exception e) { e.printStackTrace(); @@ -46,8 +59,12 @@ public class RMIClient { } - - public void doEvent(NetworkEvent event) throws Exception { + /** + * Sends a {@link NetworkEvent} to the server. + * @param event the event to send + * @throws RemoteException if any RMI error occurs + */ + public void doEvent(NetworkEvent event) throws RemoteException { stub.doEvent(event); } From 1f44e415e4626256c74dc38753b674cb46a7458a Mon Sep 17 00:00:00 2001 From: AleandroPagani Date: Sun, 26 Apr 2026 16:16:05 +0200 Subject: [PATCH 08/13] Fix: major changes to TCP server/client stack. --- .../gc14/Network/TCP/Client/TCPClient.java | 31 +++--- .../Network/TCP/Server/ClientHandler.java | 39 +++----- .../gc14/Network/TCP/Server/TCPServer.java | 95 ++++++++----------- 3 files changed, 68 insertions(+), 97 deletions(-) diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Client/TCPClient.java b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Client/TCPClient.java index 9a39808..adf63f6 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Client/TCPClient.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Client/TCPClient.java @@ -8,11 +8,10 @@ import it.polimi.ingsw.gc14.Network.NetworkEvents.AddPlayer; import java.io.*; import java.net.*; -public class TCPClient implements Serializable{ - Socket communicationSocket = null; +public class TCPClient { + Socket communicationSocket; ObjectInputStream socketReceive; ObjectOutputStream socketSend; - GameController controller; String hostname; int port; @@ -23,43 +22,44 @@ public class TCPClient implements Serializable{ this.port = port; } - public boolean start(String user, int players){ + public boolean start(String user, int proposedNPlayers){ try{ communicationSocket = new Socket(hostname, port); socketSend = new ObjectOutputStream(communicationSocket.getOutputStream()); socketReceive = new ObjectInputStream(communicationSocket.getInputStream()); - socketSend.writeObject(new AddPlayer(user, players)); + sendEvent(new AddPlayer(user, proposedNPlayers)); if(communicationSocket.getInputStream().read() == -1){ + System.out.println("Could not connect to server"); return false; } else{ - Thread listener = new Thread(() -> ReceiveMessage()); + Thread listener = new Thread(() -> receiveMessage()); listener.start(); return true; } - } - catch(Exception e){ + } catch (IOException e) { + e.printStackTrace(); return false; } + } - private void ReceiveMessage(){ + private void receiveMessage(){ while(true){ try{ Object read = socketReceive.readObject(); - if (read instanceof NetworkEvent) { //TODO non fare con instanceof - NetworkEvent event = (NetworkEvent) read; + if (read instanceof NetworkEvent event) { //TODO non fare con instanceof if(event.getIsError()) { - System.out.println(event.toString()); + System.out.println(event); } else { event.apply(controller); //clientController.view.update(); TODO } } - else if (read instanceof Game) { - controller.setModel((Game) read); + else if (read instanceof Game model) { + controller.setModel(model); } } @@ -69,11 +69,10 @@ public class TCPClient implements Serializable{ catch(ClassNotFoundException e){ throw new RuntimeException(e); } - return; } } - private void SendEvent(NetworkEvent event){ + private void sendEvent(NetworkEvent event){ try{ socketSend.writeObject(event); } diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/ClientHandler.java b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/ClientHandler.java index a989868..1a98f12 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/ClientHandler.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/ClientHandler.java @@ -1,9 +1,7 @@ package it.polimi.ingsw.gc14.Network.TCP.Server; -import it.polimi.ingsw.gc14.Controller.GameController; import it.polimi.ingsw.gc14.Model.Game; import it.polimi.ingsw.gc14.Network.NetworkEvent; -import it.polimi.ingsw.gc14.Network.EventType; import java.io.*; import java.net.*; @@ -12,12 +10,10 @@ import java.util.concurrent.BlockingQueue; public class ClientHandler implements Runnable { private Socket clientSocket; - private TCPServer server; - public ObjectInputStream in = null; - public ObjectOutputStream out = null; + public ObjectInputStream in; + public ObjectOutputStream out; List clientHandlers; BlockingQueue actionQueue; - private EventType eventType; public Socket getClientSocket() { return clientSocket; @@ -31,33 +27,24 @@ public class ClientHandler implements Runnable { @Override public void run(){ - clientLoop(); - } - - private void clientLoop(){ try{ - NetworkEvent input = null; - synchronized(in){ - in = new ObjectInputStream(clientSocket.getInputStream()); - } + in = new ObjectInputStream(clientSocket.getInputStream()); + out = new ObjectOutputStream(clientSocket.getOutputStream()); + while(true){ - try{ - input = (NetworkEvent) (in.readObject()); - if(!actionQueue.add(input)){ - System.out.println("An error occurred in inserting an action into queue"); - } - } - catch(java.io.IOException e){ - e.printStackTrace(); - } - catch (ClassNotFoundException e){ - throw new RuntimeException(e); + NetworkEvent event = (NetworkEvent) in.readObject(); + if(!actionQueue.add(event)){ + System.out.println("Error inserting action into queue"); } } } - catch (IOException e) { + catch(IOException e){ + clientHandlers.remove(this); e.printStackTrace(); } + catch(ClassNotFoundException e){ + throw new RuntimeException(e); + } } public void notifyEvent(NetworkEvent event){ diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/TCPServer.java b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/TCPServer.java index fc86f84..a8698c2 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/TCPServer.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/TCPServer.java @@ -3,6 +3,7 @@ package it.polimi.ingsw.gc14.Network.TCP.Server; import it.polimi.ingsw.gc14.Controller.GameController; import it.polimi.ingsw.gc14.LimitedList; import it.polimi.ingsw.gc14.Model.Game; +import it.polimi.ingsw.gc14.Network.EventType; import it.polimi.ingsw.gc14.Network.NetworkEvent; import it.polimi.ingsw.gc14.Network.NetworkEvents.AddPlayer; @@ -14,32 +15,29 @@ import java.util.concurrent.BlockingQueue; public class TCPServer { - int port = -1; - int ConnectedPlayers = 0; - ServerSocket serverTCP = null; - GameController gameController; + int port; + int ConnectedPlayers; + ServerSocket serverTCP; + GameController controller; BlockingQueue actionQueue; private LimitedList playerList; private List clientHandlers; - - private int getConnectedPlayers(){ return ConnectedPlayers; } public void start(){ - clientHandlers = new ArrayList<>(); try{ serverTCP = new ServerSocket(port); } catch (IOException e){ - System.out.println("Could not listen on port: " + port); + System.out.println("Could not start the server TCP on port: " + port); e.printStackTrace(); return; } - System.out.println("Listening on port: " + port); + System.out.println("Server TCP started on port: " + port); while(true){ Socket clientSocket = null; @@ -49,34 +47,42 @@ public class TCPServer { ObjectInputStream clientSocketObj = new ObjectInputStream(clientSocket.getInputStream()); NetworkEvent event = (NetworkEvent) clientSocketObj.readObject(); - synchronized (gameController){ - if(!(event instanceof AddPlayer) || (gameController.getModel() != null && gameController.getModel().getCurrentPlayerNumber() >= gameController.getModel().getNPlayers())){ - clientSocket.getOutputStream().write((int)(-1)); + if(!(event.getEventType() == EventType.ADD_PLAYER)){ + clientSocket.getOutputStream().write((int)(-1)); + clientSocket.close(); + System.out.println("Invalid parameters. Connection terminated.\n"); + } + else{ + AddPlayer eventAddPlayer = (AddPlayer) event; + if (eventAddPlayer.getProposedNPlayer() < 2 || eventAddPlayer.getProposedNPlayer() > 5) { + clientSocket.getOutputStream().write((int) (-1)); clientSocket.close(); System.out.println("Invalid parameters. Connection terminated.\n"); } - else{ - synchronized (gameController) { - AddPlayer addPlayer = (AddPlayer) event; - if(playerList.isEmpty() && (addPlayer.getProposedNPlayer() < 2 || addPlayer.getProposedNPlayer() > 5)){ - clientSocket.getOutputStream().write((int)(-1)); - clientSocket.close(); - System.out.println("Invalid parameters. Connection terminated.\n"); - } - else if(gameController.addPlayer(addPlayer.getUsername())){ - if(playerList.isEmpty()){ - Game game = new Game(addPlayer.getProposedNPlayer()); - gameController.setModel(game); - playerList.setLimit(addPlayer.getProposedNPlayer()); - } - playerList.add(addPlayer.getUsername()); - clientSocket.getOutputStream().write((int)(1)); - } + synchronized (controller) { + if (playerList.isEmpty()){ + Game model = new Game(eventAddPlayer.getProposedNPlayer()); + controller.setModel(model); + playerList.setLimit(eventAddPlayer.getProposedNPlayer()); } + if (controller.addPlayer(eventAddPlayer.getUsername())) { + playerList.add(eventAddPlayer.getUsername()); + clientSocket.getOutputStream().write((int) (1)); + System.out.println("Accepted player: " + eventAddPlayer.getUsername()); + ClientHandler clientHandler = new ClientHandler(clientSocket, clientHandlers, actionQueue); + clientHandlers.add(clientHandler); + ConnectedPlayers++; + + Thread t = new Thread(clientHandler); + t.start(); + } else { + clientSocket.getOutputStream().write((int) (-1)); + clientSocket.close(); + System.out.println("Player could not be added. Connection terminated.\n"); + } } } - // gestione di ADD_PLAYER } catch(IOException e){ e.printStackTrace(); @@ -84,38 +90,17 @@ public class TCPServer { catch(ClassNotFoundException e){ throw new RuntimeException(e); } - - System.out.println("Accepted player: " + gameController.getModel().getPlayerByUsername(clientSocket.getInetAddress().toString())); - - ConnectedPlayers++; - ClientHandler clientHandler = new ClientHandler(clientSocket, clientHandlers, actionQueue); - clientHandlers.add(clientHandler); - - //Sending model to clients - if(ConnectedPlayers == gameController.getModel().getNPlayers()){ - for (ClientHandler handler : clientHandlers) { - try { - synchronized(handler.out){ - ObjectOutputStream socketTx = new ObjectOutputStream(handler.getClientSocket().getOutputStream()); - socketTx.writeObject(gameController.getModel()); - } - } - catch(IOException e){ - e.printStackTrace(); - } - } - } - - Thread t = new Thread(clientHandler); - t.start(); } } public TCPServer(GameController gameController, int port, BlockingQueue actionQueue, LimitedList players){ this.port = port; - this.gameController = gameController; + this.ConnectedPlayers = 0; + this.serverTCP = null; + this.controller = gameController; this.actionQueue = actionQueue; this.playerList = players; + this.clientHandlers = new ArrayList<>(); } public void notifyAll(NetworkEvent event){ From 07584ec5a3450200a95a1245da9214c9dd643df8 Mon Sep 17 00:00:00 2001 From: AleandroPagani Date: Sun, 26 Apr 2026 16:33:10 +0200 Subject: [PATCH 09/13] Fix: removed unused class in ClientHandler Add: complete JavaDOC to TCPServer --- .../gc14/Network/RMI/Server/RMIServer.java | 2 +- .../Network/TCP/Server/ClientHandler.java | 3 - .../gc14/Network/TCP/Server/TCPServer.java | 62 +++++++++++++++---- 3 files changed, 51 insertions(+), 16 deletions(-) diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Server/RMIServer.java b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Server/RMIServer.java index 3578350..05152c1 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Server/RMIServer.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Server/RMIServer.java @@ -122,7 +122,7 @@ public class RMIServer implements IGameServer { /** - * Sends a model game to all RMI clients. + * Sends a game model to all RMI clients. * @param model The desired model */ public void notifyAll(Game model) throws RemoteException { diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/ClientHandler.java b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/ClientHandler.java index 1a98f12..d6de535 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/ClientHandler.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/ClientHandler.java @@ -15,9 +15,6 @@ public class ClientHandler implements Runnable { List clientHandlers; BlockingQueue actionQueue; - public Socket getClientSocket() { - return clientSocket; - } public ClientHandler(Socket clientSocket, List clientHandlers, BlockingQueue actionQueue) { this.clientSocket = clientSocket; diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/TCPServer.java b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/TCPServer.java index a8698c2..3c1d442 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/TCPServer.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/TCPServer.java @@ -13,24 +13,50 @@ import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; - +/** + * Server TCP. Accepts connections and manages all client handlers. + */ public class TCPServer { + + /** TCP port */ int port; + + /** Number of currently connected clients */ int ConnectedPlayers; - ServerSocket serverTCP; + + /** Socket TCP */ + ServerSocket socketTCP; + + /** Server game's controller */ GameController controller; + + /** Queue containing the events to be applied to the game model */ BlockingQueue actionQueue; + + /** + * List containing the usernames of joined players. + * {@link LimitedList}'s limit defines at which size the list calls its action. The limit can be set using {@link LimitedList#setLimit(int)}. + */ private LimitedList playerList; + + /** List containing all client's handlers */ private List clientHandlers; - private int getConnectedPlayers(){ - return ConnectedPlayers; - } + /** + * Starts the TCP server. + * If the first event is not AddPlayer, the request is rejected. + * If the desired number of player is invalid, the request is rejected. + * + * If this is the first player to connect, a new game model is created and passed to the controller. Additionally, the playerList's limit is set. + * If the controller successfully adds the player, the username is added to {@link #playerList} and the handler is added to {@link #clientHandlers}. + * + * If any error occurs, the server sends -1 back to the client. Otherwise, it sends 1. + */ public void start(){ try{ - serverTCP = new ServerSocket(port); + socketTCP = new ServerSocket(port); } catch (IOException e){ System.out.println("Could not start the server TCP on port: " + port); @@ -38,12 +64,12 @@ public class TCPServer { return; } System.out.println("Server TCP started on port: " + port); + Socket clientSocket; while(true){ - Socket clientSocket = null; try{ - clientSocket = serverTCP.accept(); + clientSocket = socketTCP.accept(); ObjectInputStream clientSocketObj = new ObjectInputStream(clientSocket.getInputStream()); NetworkEvent event = (NetworkEvent) clientSocketObj.readObject(); @@ -93,20 +119,32 @@ public class TCPServer { } } - public TCPServer(GameController gameController, int port, BlockingQueue actionQueue, LimitedList players){ + + /** + * Class constructor that initializes the attributes. + * @param controller The game controller + * @param port The TCP port + * @param actionQueue The action queue + * @param playerList The player's usernames list + */ + public TCPServer(GameController controller, int port, BlockingQueue actionQueue, LimitedList playerList){ this.port = port; this.ConnectedPlayers = 0; - this.serverTCP = null; - this.controller = gameController; + this.socketTCP = null; + this.controller = controller; this.actionQueue = actionQueue; - this.playerList = players; + this.playerList = playerList; this.clientHandlers = new ArrayList<>(); } + + /** Sends an action to all TCP clients */ public void notifyAll(NetworkEvent event){ clientHandlers.forEach((x) -> x.notifyEvent(event)); } + + /** Sends a game model to all TCP clients */ public void notifyAll(Game model){ clientHandlers.forEach((x) -> x.notifyModel(model)); } From bce90c2640a16a0a7a517ea72f96c6487e1dc77a Mon Sep 17 00:00:00 2001 From: AleandroPagani Date: Sun, 26 Apr 2026 16:40:49 +0200 Subject: [PATCH 10/13] Add: complete JavaDOC to ClientHandler --- .../Network/TCP/Server/ClientHandler.java | 78 +++++++++++++------ .../gc14/Network/TCP/Server/TCPServer.java | 36 ++++----- 2 files changed, 73 insertions(+), 41 deletions(-) diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/ClientHandler.java b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/ClientHandler.java index d6de535..d576816 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/ClientHandler.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/ClientHandler.java @@ -8,66 +8,98 @@ import java.net.*; import java.util.List; import java.util.concurrent.BlockingQueue; +/** + * Handles the TCP connection with a single client. + * Each instance runs on a dedicated thread and is responsible for receiving {@link NetworkEvent} from its client and adding them + * to the {@link #actionQueue}. + * It is also responsible to send events and game model updates back to the client. + */ public class ClientHandler implements Runnable { + + /** The TCP socket */ private Socket clientSocket; + + /** Input stream used to receive requests from the client */ public ObjectInputStream in; + + /** Output stream used to send objects to the client */ public ObjectOutputStream out; + + /** + * Shared list of all client handlers. + * This handler removes itself from the list when disconnected. + */ List clientHandlers; + + /** Queue containing the events to be applied to the game model */ BlockingQueue actionQueue; + /** + * Class constructor that initializes the attributes. + * @param clientSocket The socket representing the client's TCP connection + * @param clientHandlers The shared list of all active client handlers + * @param actionQueue The queue containing incoming events + */ public ClientHandler(Socket clientSocket, List clientHandlers, BlockingQueue actionQueue) { this.clientSocket = clientSocket; this.clientHandlers = clientHandlers; this.actionQueue = actionQueue; } + + /** + * Listens for incoming {@link NetworkEvent}s from the client and adds them to the {@link #actionQueue}. + * Upon disconnection, this handler removes itself from {@link #clientHandlers}. + */ @Override - public void run(){ - try{ + public void run() { + try { in = new ObjectInputStream(clientSocket.getInputStream()); out = new ObjectOutputStream(clientSocket.getOutputStream()); - - while(true){ + while (true) { NetworkEvent event = (NetworkEvent) in.readObject(); - if(!actionQueue.add(event)){ + if (!actionQueue.add(event)) { System.out.println("Error inserting action into queue"); } } - } - catch(IOException e){ + } catch (IOException e) { clientHandlers.remove(this); e.printStackTrace(); - } - catch(ClassNotFoundException e){ + } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } - public void notifyEvent(NetworkEvent event){ - synchronized(out){ - try{ + + /** + * Sends a {@link NetworkEvent} to the client. + * @param event The network event to send to the client. + */ + public void notifyEvent(NetworkEvent event) { + synchronized (out) { + try { out = new ObjectOutputStream(clientSocket.getOutputStream()); out.writeObject(event); - } - catch(IOException e){ + } catch (IOException e) { e.printStackTrace(); } } } - public void notifyModel(Game game){ - synchronized(out){ - try{ + + /** + * Sends the current game model to this client. + * @param game The current state of the game to send to the client. + */ + public void notifyModel(Game game) { + synchronized (out) { + try { out = new ObjectOutputStream(clientSocket.getOutputStream()); out.writeObject(game); - } - catch(IOException e){ + } catch (IOException e) { e.printStackTrace(); } } } - -} - - +} \ No newline at end of file diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/TCPServer.java b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/TCPServer.java index 3c1d442..16c4cfb 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/TCPServer.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/TCPServer.java @@ -43,6 +43,24 @@ public class TCPServer { private List clientHandlers; + /** + * Class constructor that initializes the attributes. + * @param controller The game controller + * @param port The TCP port + * @param actionQueue The action queue + * @param playerList The player's usernames list + */ + public TCPServer(GameController controller, int port, BlockingQueue actionQueue, LimitedList playerList){ + this.port = port; + this.ConnectedPlayers = 0; + this.socketTCP = null; + this.controller = controller; + this.actionQueue = actionQueue; + this.playerList = playerList; + this.clientHandlers = new ArrayList<>(); + } + + /** * Starts the TCP server. * If the first event is not AddPlayer, the request is rejected. @@ -120,24 +138,6 @@ public class TCPServer { } - /** - * Class constructor that initializes the attributes. - * @param controller The game controller - * @param port The TCP port - * @param actionQueue The action queue - * @param playerList The player's usernames list - */ - public TCPServer(GameController controller, int port, BlockingQueue actionQueue, LimitedList playerList){ - this.port = port; - this.ConnectedPlayers = 0; - this.socketTCP = null; - this.controller = controller; - this.actionQueue = actionQueue; - this.playerList = playerList; - this.clientHandlers = new ArrayList<>(); - } - - /** Sends an action to all TCP clients */ public void notifyAll(NetworkEvent event){ clientHandlers.forEach((x) -> x.notifyEvent(event)); From 1260c58bb6fe0b4ff472236f8baf97486484dfa8 Mon Sep 17 00:00:00 2001 From: AleandroPagani Date: Sun, 26 Apr 2026 17:03:44 +0200 Subject: [PATCH 11/13] Add: complete JavaDOC to TCPClient --- .../gc14/Network/TCP/Client/TCPClient.java | 88 +++++++++++++------ .../Network/TCP/Server/ClientHandler.java | 2 +- 2 files changed, 62 insertions(+), 28 deletions(-) diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Client/TCPClient.java b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Client/TCPClient.java index adf63f6..c69734e 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Client/TCPClient.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Client/TCPClient.java @@ -8,32 +8,62 @@ import it.polimi.ingsw.gc14.Network.NetworkEvents.AddPlayer; import java.io.*; import java.net.*; +/** + * Client TCP. Sends and receives messages with the TCP server. + */ public class TCPClient { + + /** Socket TCP */ Socket communicationSocket; + + /** Input stream used receive objects from the server */ ObjectInputStream socketReceive; + + /** Output stream used to send objects to the server */ ObjectOutputStream socketSend; + + /** Client game's controller */ GameController controller; + + /** IP address of the server to connect to */ String hostname; + + /** TCP port */ int port; - public TCPClient(GameController controller, String hostname, int port){ + + /** + * Class constructor that initializes the attributes. + * @param controller The game controller + * @param hostname The IP address of the server + * @param port The TCP port of the server + */ + public TCPClient(GameController controller, String hostname, int port) { this.controller = controller; this.hostname = hostname; this.port = port; } - public boolean start(String user, int proposedNPlayers){ - try{ + + /** + * Starts the TCP connection with the server. + * Sends an {@link AddPlayer} event, if the server responds with {@code -1}, the connection is refused and the method returns {@code false}. + * Otherwise, a listener thread is started. + * @param user The username of the player + * @param proposedNPlayers The desired number of players for the game + * @return true if the connection is successful, false otherwise. + */ + public boolean start(String user, int proposedNPlayers) { + try { communicationSocket = new Socket(hostname, port); socketSend = new ObjectOutputStream(communicationSocket.getOutputStream()); socketReceive = new ObjectInputStream(communicationSocket.getInputStream()); sendEvent(new AddPlayer(user, proposedNPlayers)); - if(communicationSocket.getInputStream().read() == -1){ + if (communicationSocket.getInputStream().read() == -1) { System.out.println("Could not connect to server"); return false; - } - else{ + } else { Thread listener = new Thread(() -> receiveMessage()); listener.start(); return true; @@ -42,43 +72,47 @@ public class TCPClient { e.printStackTrace(); return false; } - } - private void receiveMessage(){ - while(true){ - try{ - Object read = socketReceive.readObject(); - if (read instanceof NetworkEvent event) { //TODO non fare con instanceof - if(event.getIsError()) { + /** + * Listens continuously for incoming objects from the server. + * - If the received object is a {@link NetworkEvent} flagged as an error, it is printed. + * - If the received object is a valid {@link NetworkEvent}, it is applied to the game controller. + * - If the received object is a {@link Game} model, the controller's model is set. + */ + private void receiveMessage() { + while (true) { + try { + Object read = socketReceive.readObject(); + if (read instanceof NetworkEvent event) { //TODO: avoid instanceof + if (event.getIsError()) { System.out.println(event); } else { event.apply(controller); - //clientController.view.update(); TODO + //clientController.view.update(); TODO } - } - else if (read instanceof Game model) { + } else if (read instanceof Game model) { controller.setModel(model); } - - } - catch(IOException e){ + } catch (IOException e) { e.printStackTrace(); - } - catch(ClassNotFoundException e){ + } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } } - private void sendEvent(NetworkEvent event){ - try{ + + /** + * Sends a {@link NetworkEvent} to the server. + * @param event The NetworkEvent to send. + */ + private void sendEvent(NetworkEvent event) { + try { socketSend.writeObject(event); - } - catch (IOException e) { + } catch (IOException e) { e.printStackTrace(); } } - -} +} \ No newline at end of file diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/ClientHandler.java b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/ClientHandler.java index d576816..07864f0 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/ClientHandler.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/TCP/Server/ClientHandler.java @@ -19,7 +19,7 @@ public class ClientHandler implements Runnable { /** The TCP socket */ private Socket clientSocket; - /** Input stream used to receive requests from the client */ + /** Input stream used to receive objects from the client */ public ObjectInputStream in; /** Output stream used to send objects to the client */ From 73b5b6eba555240ffdb5d20459636a9117c3c4e6 Mon Sep 17 00:00:00 2001 From: AleandroPagani Date: Wed, 29 Apr 2026 17:14:45 +0200 Subject: [PATCH 12/13] Add: ClientLauncherTUI. Connection and model sending works. Note: ClientController.view is commented out since class TUI is still missing --- .../it/polimi/ingsw/gc14/ClientLauncher.java | 28 ---------- .../polimi/ingsw/gc14/ClientLauncherTUI.java | 54 +++++++++++++++++++ .../gc14/Controller/ClientController.java | 12 +++-- .../ingsw/gc14/Model/GamePackage/Board.java | 4 +- .../RMI/Client/ClientCallbackImpl.java | 3 +- .../gc14/Network/RMI/Client/RMIClient.java | 1 - .../Network/RMI/Common/IClientCallback.java | 3 +- .../gc14/Network/RMI/Server/RMIServer.java | 5 +- .../it/polimi/ingsw/gc14/ServerLauncher.java | 19 ++++--- src/main/java/module-info.java | 9 +++- 10 files changed, 91 insertions(+), 47 deletions(-) delete mode 100644 src/main/java/it/polimi/ingsw/gc14/ClientLauncher.java create mode 100644 src/main/java/it/polimi/ingsw/gc14/ClientLauncherTUI.java diff --git a/src/main/java/it/polimi/ingsw/gc14/ClientLauncher.java b/src/main/java/it/polimi/ingsw/gc14/ClientLauncher.java deleted file mode 100644 index fd8a3f8..0000000 --- a/src/main/java/it/polimi/ingsw/gc14/ClientLauncher.java +++ /dev/null @@ -1,28 +0,0 @@ -package it.polimi.ingsw.gc14; -import java.util.Scanner; - -public class ClientLauncher { - public void main() { - Scanner scanner = new Scanner(System.in); - - System.out.println("Selezionare nome utente: "); - String username = scanner.next(); - System.out.println(username); - - System.out.println("Selezionare numero di giocatori desiderato: "); - int proposedNumPlayers = scanner.nextInt(); - System.out.println(proposedNumPlayers); - - System.out.println("Selezionare RMI[0] o TCP[1]: "); - int networkType = scanner.nextInt(); - System.out.println(networkType); - - scanner.close(); // chiudi solo alla fine - - if (networkType == 0) { - return; - } else if (networkType == 1) { - return; - } - } -} \ No newline at end of file diff --git a/src/main/java/it/polimi/ingsw/gc14/ClientLauncherTUI.java b/src/main/java/it/polimi/ingsw/gc14/ClientLauncherTUI.java new file mode 100644 index 0000000..bb89ac2 --- /dev/null +++ b/src/main/java/it/polimi/ingsw/gc14/ClientLauncherTUI.java @@ -0,0 +1,54 @@ +package it.polimi.ingsw.gc14; +import it.polimi.ingsw.gc14.Controller.ClientController; +import it.polimi.ingsw.gc14.Network.RMI.Client.RMIClient; +import it.polimi.ingsw.gc14.View.IView; + +import java.util.Scanner; + +public class ClientLauncherTUI { + public void main() throws InterruptedException { + ClientController controller = new ClientController(); + + Scanner scanner = new Scanner(System.in); + + System.out.println("Selezionare nome utente: "); + String username = scanner.next(); + System.out.println(username); + + System.out.println("Selezionare numero di giocatori desiderato: "); + int proposedNumPlayers = scanner.nextInt(); + System.out.println(proposedNumPlayers); + + System.out.println("Selezionare RMI[0] o TCP[1]: "); + int networkType = scanner.nextInt(); + System.out.println(networkType); + + scanner.close(); + + if (networkType == 0) { + RMIClient client = new RMIClient("localhost", 1099); + if (client.connect(username, proposedNumPlayers, controller)) { + System.out.println("CLIENT CONNESSO DAJE"); + } else { + System.out.println("NON CONNESSO D:"); + } + + while(true) { + System.out.flush(); + if (controller.localModel!=null) { + System.out.println("MODEL SETTATO"); + } + Thread.sleep(500); + } + + + + + + + + } else if (networkType == 1) { + return; + } + } +} \ No newline at end of file diff --git a/src/main/java/it/polimi/ingsw/gc14/Controller/ClientController.java b/src/main/java/it/polimi/ingsw/gc14/Controller/ClientController.java index d206d22..1da7933 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Controller/ClientController.java +++ b/src/main/java/it/polimi/ingsw/gc14/Controller/ClientController.java @@ -6,9 +6,9 @@ import it.polimi.ingsw.gc14.View.IView; public class ClientController { - private Game localModel; + public Game localModel; public GameController localController; - public final IView view; + public IView view=null; public ClientController(IView view,Game localModel) { this.view = view; @@ -16,12 +16,18 @@ public class ClientController { this.localController = new GameController(localModel); } + public ClientController() { + this.localController = new GameController(localModel); + } + public void setModel(Game model) { this.localModel = model; localController.setModel(model); - localModel.addObserver((Observer) view); // registra la view come observer + // localModel.addObserver((Observer) view); // registra la view come observer } + + public void onError(String message) { view.showError(message); } diff --git a/src/main/java/it/polimi/ingsw/gc14/Model/GamePackage/Board.java b/src/main/java/it/polimi/ingsw/gc14/Model/GamePackage/Board.java index 55a17ee..4fda653 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Model/GamePackage/Board.java +++ b/src/main/java/it/polimi/ingsw/gc14/Model/GamePackage/Board.java @@ -111,9 +111,9 @@ public class Board implements Serializable { ArrayList buildingDeck = new ArrayList<>(DecksCreator.loadBuildingDeckByEra(1)); Collections.shuffle(buildingDeck); if(nTotem==2) - upperListBuilding= buildingDeck.subList(0,1); + upperListBuilding = new ArrayList<>(buildingDeck.subList(0,1)); else - upperListBuilding= buildingDeck.subList(0,2); + upperListBuilding = new ArrayList<>(buildingDeck.subList(0,2)); } /** diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Client/ClientCallbackImpl.java b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Client/ClientCallbackImpl.java index 928fa52..5b16b76 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Client/ClientCallbackImpl.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Client/ClientCallbackImpl.java @@ -5,6 +5,7 @@ import it.polimi.ingsw.gc14.Model.Game; import it.polimi.ingsw.gc14.Network.NetworkEvent; import it.polimi.ingsw.gc14.Network.RMI.Common.IClientCallback; +import java.io.Serializable; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; @@ -13,7 +14,7 @@ import java.rmi.server.UnicastRemoteObject; * RMI client callback implementation of {@link IClientCallback}. * Receives notifications from the server and updates the client game model. */ -public class ClientCallbackImpl extends UnicastRemoteObject implements IClientCallback { +public class ClientCallbackImpl extends UnicastRemoteObject implements IClientCallback, Serializable { /** The client controller used to apply events and update the model */ private final ClientController clientController; diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Client/RMIClient.java b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Client/RMIClient.java index 84d797f..19bd574 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Client/RMIClient.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Client/RMIClient.java @@ -7,7 +7,6 @@ import it.polimi.ingsw.gc14.Controller.ClientController; import it.polimi.ingsw.gc14.Network.NetworkEvent; import it.polimi.ingsw.gc14.Network.RMI.Common.IClientCallback; import it.polimi.ingsw.gc14.Network.RMI.Common.IGameServer; -import it.polimi.ingsw.gc14.Network.RMI.Server.RMIServer; /** * Client RMI. Uses the methods exposed by the server RMI. diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Common/IClientCallback.java b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Common/IClientCallback.java index 0292fcc..c7fa94d 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Common/IClientCallback.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Common/IClientCallback.java @@ -3,9 +3,10 @@ package it.polimi.ingsw.gc14.Network.RMI.Common; import it.polimi.ingsw.gc14.Model.Game; import it.polimi.ingsw.gc14.Network.NetworkEvent; +import java.io.Serializable; import java.rmi.*; -public interface IClientCallback extends Remote { +public interface IClientCallback extends Remote, Serializable { void onGameInit(Game model) throws RemoteException; void onAction(NetworkEvent action) throws RemoteException; } \ No newline at end of file diff --git a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Server/RMIServer.java b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Server/RMIServer.java index 05152c1..6fadf03 100644 --- a/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Server/RMIServer.java +++ b/src/main/java/it/polimi/ingsw/gc14/Network/RMI/Server/RMIServer.java @@ -21,7 +21,7 @@ import java.rmi.*; /** * Server RMI. Exposes a method to join the game and one to execute an event. */ -public class RMIServer implements IGameServer { +public class RMIServer extends UnicastRemoteObject implements IGameServer { /** Server game's controller */ private GameController controller; @@ -88,12 +88,13 @@ public class RMIServer implements IGameServer { playerList.setLimit(preferredInt); } if (controller.addPlayer(username)) { - playerList.add(username); clients.put(username, callback); + playerList.add(username); return true; } return false; } + } diff --git a/src/main/java/it/polimi/ingsw/gc14/ServerLauncher.java b/src/main/java/it/polimi/ingsw/gc14/ServerLauncher.java index df3c776..d1650d9 100644 --- a/src/main/java/it/polimi/ingsw/gc14/ServerLauncher.java +++ b/src/main/java/it/polimi/ingsw/gc14/ServerLauncher.java @@ -34,7 +34,7 @@ import java.util.concurrent.LinkedBlockingQueue; public class ServerLauncher { /** - * Queue containing the events to be applied to the game model. + * Queue containinetworkTypeng the events to be applied to the game model. * Thread safe by design. */ BlockingQueue actionQueue; @@ -109,13 +109,15 @@ public class ServerLauncher { ServerLauncher launcher = new ServerLauncher(actionQueue, gameController, serverRMI, serverTCP); playerList.setAction(()->{ - try { - launcher.run(); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } catch (RemoteException e) { - throw new RuntimeException(e); - } + new Thread(()->{ + try { + launcher.run(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } catch (RemoteException e) { + throw new RuntimeException(e); + } + }).start(); }); serverRMI.start(); @@ -132,6 +134,7 @@ public class ServerLauncher { */ public void run() throws InterruptedException, RemoteException { // Game creation + System.out.println("NOTIFICO MODEL"); serverRMI.notifyAll(gameController.getModel()); serverTCP.notifyAll(gameController.getModel()); diff --git a/src/main/java/module-info.java b/src/main/java/module-info.java index 732a715..e178647 100644 --- a/src/main/java/module-info.java +++ b/src/main/java/module-info.java @@ -8,7 +8,14 @@ module it.polimi.ingsw.gc14 { opens it.polimi.ingsw.gc14 to javafx.fxml, com.google.gson; opens it.polimi.ingsw.gc14.Model to com.google.gson; + opens it.polimi.ingsw.gc14.Model.GamePackage to com.google.gson; exports it.polimi.ingsw.gc14; - opens it.polimi.ingsw.gc14.Model.GamePackage to com.google.gson; + + // RMI + exports it.polimi.ingsw.gc14.Network.RMI.Common to java.rmi; + exports it.polimi.ingsw.gc14.Network.RMI.Server to java.rmi; + exports it.polimi.ingsw.gc14.Network.RMI.Client to java.rmi; + exports it.polimi.ingsw.gc14.Network to java.rmi; + exports it.polimi.ingsw.gc14.Model to java.rmi, com.google.gson; } \ No newline at end of file From 6cb0564761d2eb09b7e0138b87a4bfbb5297ca67 Mon Sep 17 00:00:00 2001 From: AleandroPagani Date: Wed, 29 Apr 2026 17:48:16 +0200 Subject: [PATCH 13/13] Fix: output --- .../java/it/polimi/ingsw/gc14/ClientLauncherTUI.java | 9 ++++----- src/main/java/it/polimi/ingsw/gc14/ServerLauncher.java | 2 +- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/src/main/java/it/polimi/ingsw/gc14/ClientLauncherTUI.java b/src/main/java/it/polimi/ingsw/gc14/ClientLauncherTUI.java index bb89ac2..8da0d9e 100644 --- a/src/main/java/it/polimi/ingsw/gc14/ClientLauncherTUI.java +++ b/src/main/java/it/polimi/ingsw/gc14/ClientLauncherTUI.java @@ -28,21 +28,20 @@ public class ClientLauncherTUI { if (networkType == 0) { RMIClient client = new RMIClient("localhost", 1099); if (client.connect(username, proposedNumPlayers, controller)) { - System.out.println("CLIENT CONNESSO DAJE"); + System.out.println("Succesfully connected to RMI server\n\n"); } else { - System.out.println("NON CONNESSO D:"); + System.out.println("RMI connection refused\n\n"); } while(true) { System.out.flush(); if (controller.localModel!=null) { - System.out.println("MODEL SETTATO"); + break; } Thread.sleep(500); } - - + System.out.println("Model set\n\n"); diff --git a/src/main/java/it/polimi/ingsw/gc14/ServerLauncher.java b/src/main/java/it/polimi/ingsw/gc14/ServerLauncher.java index d1650d9..9c8a10e 100644 --- a/src/main/java/it/polimi/ingsw/gc14/ServerLauncher.java +++ b/src/main/java/it/polimi/ingsw/gc14/ServerLauncher.java @@ -134,7 +134,7 @@ public class ServerLauncher { */ public void run() throws InterruptedException, RemoteException { // Game creation - System.out.println("NOTIFICO MODEL"); + System.out.println("\n\nNotifying model"); serverRMI.notifyAll(gameController.getModel()); serverTCP.notifyAll(gameController.getModel());