我正在编写一个虚拟运输应用程序。客户端发送产品,服务器保留所有发送的产品。
现在服务器 - 因为它只是虚拟的 - 每分钟更新产品的状态(发送 -> 接受 -> 发货 -> 接收),现在我希望服务器在更新状态时更新相应的客户端.
大多数 RMI 信息我都只讨论客户端 -> 服务器..但我需要我的服务器为此调用我的客户端..
希望大家帮帮忙!
最佳答案
服务器到客户端的通信在所有远程处理技术(包括 RMI)中都是一个雷区。这可能就是您努力寻找有关该主题的大量文档的原因。对于受控环境中的虚拟程序,以下方法可行并且是最简单的方法。请注意,已省略所有错误处理。
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
interface ClientRemote extends Remote {
public void doSomething() throws RemoteException;
}
interface ServerRemote extends Remote {
public void registerClient(ClientRemote client) throws RemoteException;
}
class Client implements ClientRemote {
public Client() throws RemoteException {
UnicastRemoteObject.exportObject(this, 0);
}
@Override
public void doSomething() throws RemoteException {
System.out.println("Server invoked doSomething()");
}
}
class Server implements ServerRemote {
private volatile ClientRemote client;
public Server() throws RemoteException {
UnicastRemoteObject.exportObject(this, 0);
}
@Override
public void registerClient(ClientRemote client) throws RemoteException {
this.client = client;
}
public void doSomethingOnClient() throws RemoteException {
client.doSomething();
}
}
用法:在服务器上创建一个服务器对象,将它添加到您的 RMI 注册表并在客户端上查找它。
还有其他技术可以使客户端通知更容易,Java 消息服务 (JMS) 通常用于此目的。
关于java - 更新时从服务器到客户端的 RMI 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9633638/