PDA

View Full Version : [JAVA] RMI Comunicazione fra Server e Client


JohnMarston
30-01-2016, 12:58
Ciao,
sto cercando di capire come creare un canale in modo tale che il client resti in ascolto e stampi i valori passati dal server. Mancano dei blocchi di codice, semplicemente perché non ho idea come andare avanti.

Questa è la classe server

public class Server {
RemoteImpl impl;

public void Server() {
}

public void timer(){
try {
impl = new RemoteImpl();
Registry reg = LocateRegistry.createRegistry(Constant.RMI_PORT);
reg.bind(Constant.RMI_ID, impl);
System.out.println("Server Partito!");

} catch (Exception exc) {
System.out.println("SERVER - RMI Eccezione "+exc);
}
final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(new Runnable(){
@Override
public void run(){
try {
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date today = Calendar.getInstance().getTime();
String reportDate = df.format(today);
System.out.println("Server: Time " + reportDate);
impl.getTimeServer(reportDate);
} catch (Exception exc) {
System.out.println("SERVER - Timer Eccezione "+exc);
}
}
}, 0, 1, TimeUnit.SECONDS);
}

public static void main(String[] args) throws RemoteException, AlreadyBoundException {
new Server().timer();
}

}


Questa è l'interfaccia


public class RemoteImpl extends UnicastRemoteObject implements TestRemote{

protected RemoteImpl() throws RemoteException {
super();

}
@Override
public boolean isLoginValid(String username) throws RemoteException {
if(username.equals("test")){
return true;
}
return false;
}

@Override
public void getTimeServer(String time) throws RemoteException {
System.out.println("RemoteImpl: Time "+time);
}

}



Questo è il client

public class Client {

public Client() throws RemoteException, NotBoundException {
System.out.println("RMI_PORT "+Constant.RMI_PORT);
System.out.println("RMI_ID "+Constant.RMI_ID);

Registry registry = LocateRegistry.getRegistry("localhost", Constant.RMI_PORT);
TestRemote remote = (TestRemote)registry.lookup(Constant.RMI_ID);

System.out.println(remote.isLoginValid("test"));
}

public static void main(String[] args)throws RemoteException, NotBoundException {
new Client();

}

}



In pratica il client dovrebbe continuare a stampare la data che il server passa e quest'ultimo dovrebbe consentire a più client di collegarsi.