im观察者RMI模式几乎没有问题,这里有一些代码:
完成工作的类:
public class GestoreGame implements Serializable {
int numeroG;
public static final long VERSION=2L;
String nomep;
public static int numeroGiocatori;
public GestoreGame(String nome,int numero){
numeroG=numero;
nomep=nome;
}
public int getcoda(){
return numeroGiocatori;
}
public synchronized void addGiocatore1() throws RemoteException{
numeroGiocatori++;
}
}
公共类服务器扩展Observable实现Serializable,serverInterface { //可观察 public static final long VERSION = 1L; GestoreGame x; 公共服务器()引发RemoteException {
Registry reg=LocateRegistry.createRegistry(1098);
reg.rebind("gioco",this);
x=new GestoreGame("Pippo",3);
System.out.println("[Server] started");
while(true){
}
}
@Override
public synchronized void addGiocatore(Observer c) throws RemoteException,InterruptedException {
x.addGiocatore1();
addobserver(c);
setChanged();
notifyObservers("UPDATE STATUS"+x.getcoda());
}
public static void main(String[] args) throws RemoteException {
new server();
}}
和服务器界面:
public interface serverInterface extends Remote {
public void addGiocatore(Observer c) throws RemoteException;
}
现在我有两个带有单独主程序的“客户端”来启动它们,因为如果我尝试用线程模拟更多客户端,它会很好地工作,但是当我使用不同的类连接到服务器时,它就没有。 >
client1:
public class client extends UnicastRemoteObject implements clientInterface,Observer{
serverInterface y;
public client() throws RemoteException,NotBoundException,InterruptedException {
super();
Registry registry = LocateRegistry.getRegistry("localhost",1098);
y = (serverInterface) registry.lookup("gioco");
miAggiungo(this);
}
@Override
public synchronized void miAggiungo(client c) throws RemoteException,InterruptedException {
System.out.println(Thread.currentThread().getName()+" Richiesta di essere aggiunto alla lista dei giocatori in attesa");
y.addGiocatore(c);
}
@Override
public synchronized void update(Observable o,Object arg) {
System.out.println(o+Thread.currentThread().getName()+" responso: "+arg);
}
public static void main(String[] args) throws InterruptedException,RemoteException,NotBoundException {
new client();
}}
和client2基本上与client1的代码完全相同...但是当我同时运行两个客户端时,我会得到
Server.server@387c703b主要响应:更新状态1
对于我同时运行的两个客户端,当我期望第二个客户端运行时,我都会看到“ UPDATE STATUS2”,每次客户端之一调用miAggiungo方法时,该值都会增加numeroGiocatori。
任何提示?感谢您的帮助。