Skip to content

Instantly share code, notes, and snippets.

@sixhat
Created May 14, 2018 08:54
Show Gist options
  • Save sixhat/5ffa42e4b64440147e6eb56a5487f333 to your computer and use it in GitHub Desktop.
Save sixhat/5ffa42e4b64440147e6eb56a5487f333 to your computer and use it in GitHub Desktop.
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
public class BoardServer implements Board {
private ArrayList<String> jogadores;
private String turno;
private int[] tabuleiro;
public BoardServer() {
jogadores = new ArrayList<>();
turno = "";
tabuleiro = new int[9];
}
@Override
public synchronized int[] play(int pos, String nome) throws RemoteException {
if (nome.equals(turno)) {
if (tabuleiro[pos] == 0) {
int indice = jogadores.indexOf(nome);
tabuleiro[pos] = indice + 1;
turno = jogadores.get(1 - indice);
}
}
notifyAll();
return tabuleiro;
}
@Override
public synchronized int[] getBoard(String nome) throws RemoteException {
if (!jogadores.contains(nome) && jogadores.size() < 2) {
jogadores.add(nome);
}
if (jogadores.size() == 1) {
turno = nome;
}
if (jogadores.size() == 2) {
notifyAll();
}
while (!turno.equals(nome) || jogadores.size() < 2) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return tabuleiro;
}
public static void main(String[] args) {
BoardServer galo = new BoardServer();
try {
Registry reg = LocateRegistry.getRegistry("127.0.0.1");
Board jogo = (Board) UnicastRemoteObject.exportObject(galo, 0);
reg.rebind("Galitos", jogo);
System.out.println("-- Server Ready!!!! Fight!!");
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment