如何使用Java RMI实现观察者模式?

9

我有一个客户端在服务器上启动了一个长时间运行的进程。定期地,我想向用户展示后台正在发生的事情。最简单的方法是轮询服务器,但我想知道是否有一种实现观察者模式的方法。不幸的是,我正在使用RMI与服务器通信,我担心我必须将客户端转换为RMI服务器才能实现这一点。

我是否错过了其他方法?


1
我也在尝试做这件事,而且我得出了同样的结论......RMI有点糟糕! :) - JohnIdol
1
https://sandny.com/2017/05/18/java-rmi-observer-slider/ - ricky
4个回答


3

RMI通常支持双向通信。(是的,设置和其他任何操作都很麻烦。)

然而,通过CGI脚本工作的HTTP传输不支持它。


当我在我的代码中使用LocateRegistry.createRegistry()启动服务器时(而不是使用Sun提供的可执行文件),这仍然适用吗? - Aaron Digulla
"+1" 对于 "(而且,RMI 的设置和其他任何操作都很麻烦。)" 告诉我的学校这件事。 - Luc

2

综合所有答案,我使用服务器通过注册表公开其存根来实现客户端和服务器之间的双向RMI。

  1. 客户端从rmi注册表获取服务器的存根。
  2. 然后,客户端将其存根作为观察者放入服务器的addObserver方法中。
  3. 服务器使用此存根通知客户端。

以下代码将更好地说明此过程:

import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
import java.util.Observable;
import java.util.Observer;
import java.net.*;

import javax.rmi.ssl.SslRMIClientSocketFactory;
import javax.rmi.ssl.SslRMIServerSocketFactory;

interface ReceiveMessageInterface extends Remote
{
    /**
     * @param x
     * @throws RemoteException
     */
    void receiveMessage(String x) throws RemoteException;

    /**
     * @param observer
     * @throws RemoteException
     */
    void addObserver(Remote observer) throws RemoteException;
}

/**
 * 
 */
class RmiClient extends UnicastRemoteObject
{
    /**
     * @param args
     */
    static public void main(String args[])
    {
        ReceiveMessageInterface rmiServer;
        Registry registry;
        String serverAddress = args[0];
        String serverPort = args[1];
        String text = args[2];
        System.out.println("sending " + text + " to " + serverAddress + ":" + serverPort);
        try
        { // Get the server's stub
            registry = LocateRegistry.getRegistry(serverAddress, (new Integer(serverPort)).intValue());
            rmiServer = (ReceiveMessageInterface) (registry.lookup("rmiServer"));

            // RMI client will give a stub of itself to the server
            Remote aRemoteObj = (Remote) UnicastRemoteObject.exportObject(new RmiClient(), 0);
            rmiServer.addObserver(aRemoteObj);

            // call the remote method
            rmiServer.receiveMessage(text);
            // update method will be notified
        }
        catch (RemoteException e)
        {
            e.printStackTrace();
        }
        catch (NotBoundException e)
        {
            System.err.println(e);
        }
    }

    public void update(String a) throws RemoteException
    {
        // update should take some serializable object as param NOT Observable
        // and Object
        // Server callsbacks here
    }
}

/**
 * 
 */
class RmiServer extends Observable implements ReceiveMessageInterface
{
    String address;
    Registry registry;

    /**
     * {@inheritDoc}
     */
    public void receiveMessage(String x) throws RemoteException
    {
        System.out.println(x);
        setChanged();
        notifyObservers(x + "invoked me");
    }

    /**
     * {@inheritDoc}
     */
    public void addObserver(final Remote observer) throws RemoteException
    {
        // This is where you plug in client's stub
        super.addObserver(new Observer()
        {
            @Override
            public void update(Observable o,
                Object arg)
            {
                try
                {
                    ((RmiClient) observer).update((String) arg);
                }
                catch (RemoteException e)
                {

                }
            }
        });
    }

    /**
     * @throws RemoteException
     */
    public RmiServer() throws RemoteException
    {
        try
        {
            address = (InetAddress.getLocalHost()).toString();
        }
        catch (Exception e)
        {
            System.out.println("can't get inet address.");
        }
        int port = 3232;
        System.out.println("this address=" + address + ",port=" + port);
        try
        {
            registry = LocateRegistry.createRegistry(port);
            registry.rebind("rmiServer", this);
        }
        catch (RemoteException e)
        {
            System.out.println("remote exception" + e);
        }
    }

    /**
     * 
     * @param args
     */
    static public void main(String args[])
    {
        try
        {
            RmiServer server = new RmiServer();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            System.exit(1);
        }
    }
}

基于你的代码,当 RmiServer 类实现 addObserver 方法时,RmiClient 类可以在服务器上使用。那么这个 RmiClient 类是在客户端和服务器中都定义的吗? - KUN

1

我认为你没有漏掉任何东西。唯一的两种方法是定期调用服务器并检查状态(轮询),或者注册一个回调,服务器会定期调用它(你的客户端必须公开一个方法)。在我看来,轮询是处理这个问题的完全合理的方式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接