【发布时间】:2013-12-20 12:45:42
【问题描述】:
我正在尝试使用 Java RMI 在分布式系统中实现用于组通信的中间件。
在那里,我需要向服务器发送一个对象并对其进行修改。因此,更改应该反映在客户端。
例如,我将给出Oracle网站上最常见的教程:
X.java
public class X implements Serializable, Remote{
public int x; // defined as public, just be simple.
}
Hello.java
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Hello extends Remote {
String sayHello(X c) throws RemoteException;
}
服务器.java
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;
public class Server implements Hello {
public Server() {
}
public String sayHello(X c) {
c.x = 10;
return "Hello, world!";
}
public static void main(String args[]) {
try {
Server obj = new Server();
Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);
LocateRegistry.createRegistry(1099);
// Bind the remote object's stub in the registry
Registry registry = LocateRegistry.getRegistry();
registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
客户端.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
public int x = 4;
private Client() {
}
public static void main(String[] args) {
String host = (args.length < 1) ? null : args[0];
try {
Registry registry = LocateRegistry.getRegistry(host);
Hello stub = (Hello) registry.lookup("Hello");
X x = new X();
String response = stub.sayHello(x);
System.out.println("response: " + x.x);
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
我的问题是,即使我在服务器端的对象 c 中更新 x 的值,它也不会反映到客户端。我可以简单地使用return 来获取更新的值,但我打算使用这种方法来实现服务器的多播功能。
谁能解释为什么?如果我需要这样做,该怎么做?
【问题讨论】:
标签: java rmi remote-access