如何在远程服务器上使用RMI?

时间:2014-08-06 13:32:20

标签: java rmi remote-server

我正在尝试新技术:RMI。我试过this sample,它适用于localhost。然后我在VPS上尝试了它:将RemoteHelloServiceImpl.class和RemoteHelloService.class复制到VSP,启动服务器 - 它的工作原理。然后我在HelloServiceClient

中更改了这个字符串
Registry registry = LocateRegistry.getRegistry("localhost", 2099);

到这个

Registry registry = LocateRegistry.getRegistry("178.62.30.124", 2099);

编译并运行。

抓住了这个例外:

  

线程“main”中的异常java.rmi.ConnectException:Connection拒绝主机:127.0.1.1;嵌套异常是:...

为什么选择127.0.1.1?我是否需要更改其他任何内容才能使用远程服务器?

最后一个:当我只运行2个java类时,该示例有效,但this page表示我需要运行rmiregistry;那么,为什么我需要它(rmiregistry)?

更新:

RemoteHelloService.java

import java.rmi.*;

public interface RemoteHelloService extends Remote {

    Object sayHello(String name) throws RemoteException;

}

RemoteHelloServiceImpl.java

import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;

public class RemoteHelloServiceImpl implements RemoteHelloService {

    public static final String BINDING_NAME = "sample/HelloService";

    public Object sayHello(String name) {
        String string = "Hello, " + name + "! It is " + System.currentTimeMillis() + " ms now";
        try {
            System.out.println(name + " from " + UnicastRemoteObject.getClientHost());
        } catch (ServerNotActiveException e) {
            System.out.println(e.getMessage());
        }
        if ("Killer".equals(name)) {
            System.out.println("Shutting down...");
            System.exit(1);
        }
        return string;
    }

    public static void main(String... args) throws Exception {
        System.out.print("Starting registry...");
        final Registry registry = LocateRegistry.createRegistry(2099);
        System.out.println(" OK");

        final RemoteHelloService service = new RemoteHelloServiceImpl();
        Remote stub = UnicastRemoteObject.exportObject(service, 0);

        System.out.print("Binding service...");
        registry.bind(BINDING_NAME, stub);
        System.out.println(" OK");

        while (true) {
            Thread.sleep(Integer.MAX_VALUE);
        }
    }
}

HelloServiceClient.java

import java.rmi.registry.*;

public class HelloServiceClient {

    public static void main(String... args) throws Exception {
        Registry registry = LocateRegistry.getRegistry("178.62.30.124", 2099);
        RemoteHelloService service = (RemoteHelloService) registry.lookup("sample/HelloService");
        String[] names = { "John", "Jan", "Иван", "Johan", "Hans", "Bill", "Kill" };
        for (String name : names) {
            System.out.println(service.sayHello(name));
        }
    }

}

0 个答案:

没有答案