2012-03-09 103 views
2

我正在写一个虚拟的运输应用程序。客户端发送产品,服务器保留所有发送的产品。现在服务器 - 因为它只是虚拟的 - 每分钟更新一次产品的状态(SEND - > ACCEPTED - > SHIPPED - > RECEIVED),现在我希望服务器在更新对应的客户端时更新州。RMI通知从服务器到客户端更新

我恶魔只有约客户谈大多数RMI信息 - >服务器..但我需要我的服务器调用我的客户对这个..

希望你们能帮助!

回答

4

服务器到客户端通信是有点在所有的远程访问技术,包括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)通常用于此目的。

+0

当我在服务器上调用'doSomethingOnClient()'时,我在服务器控制台而不是客户端控制台上调用了'服务器调用doSomething()'! (我也不得不让'ClientRemote'实现'Serializable'使它可以运行。)我在做什么错了? – 2017-01-16 16:31:59

+0

发现问题。不必让客户端对象为“Serializable”,而必须在客户端RMI注册表中注册该对象,并在客户端启动rmiregistry(所以基本上双方都是'服务器') – 2017-01-17 08:33:41

0

您的客户可以很经常会问到服务器,并进行自我更新,也可以为它们是连接到它RMI服务器和服务器轨道客户端和客户端程序使用RMI回调客户端时,服务器值changed.You可以看看SNMP协议它支持回调(snmp陷阱

相关问题