Files
Progetto-ingegneria-del-sof…/src/main/java/it/polimi/ingsw/gc14/ServerLauncher.java
T
2026-04-24 18:36:50 +02:00

87 lines
3.2 KiB
Java

package it.polimi.ingsw.gc14;
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;
import it.polimi.ingsw.gc14.Network.RMI.Server.RMIServer;
import it.polimi.ingsw.gc14.Network.TCP.Server.TCPServer;
import java.rmi.RemoteException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class ServerLauncher {
BlockingQueue<NetworkEvent> actionQueue;
GameController gameController;
RMIServer serverRMI;
TCPServer serverTCP;
static LimitedList<String> players;
public ServerLauncher(BlockingQueue<NetworkEvent> actionQueue, GameController gameController, RMIServer serverRMI, TCPServer serverTCP) {
this.actionQueue = actionQueue;
this.serverRMI = serverRMI;
this.gameController = gameController;
this.serverTCP = serverTCP;
this.players = new LimitedList<>(5, ()->{
try {
run();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (RemoteException e) {
throw new RuntimeException(e);
}
});
}
public boolean doFirstEven() 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;
}
}
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
BlockingQueue<NetworkEvent> actionQueue = new LinkedBlockingQueue<>();
GameController gameController = new GameController();
RMIServer serverRMI = new RMIServer(gameController, 1099, actionQueue, players);
TCPServer serverTCP = new TCPServer(gameController, 8080, actionQueue, players);
ServerLauncher launcher = new ServerLauncher(actionQueue, gameController, serverRMI, serverTCP);
launcher.run();
}
public void run() throws InterruptedException, RemoteException {
serverRMI.notifyAll(gameController.getModel());
//serverTCP.broadcastUpdate(model);
while (true) {
try {
this.doFirstEven();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
} catch (RemoteException e) {
throw new RuntimeException(e);
}
}
}
}