连接客户端 - 服务器RMI

时间:2013-10-30 16:05:23

标签: java rmi

如果服务器是远程的(不是与客户端在同一台机器上),我很困惑客户端如何实际连接到服务器。我的代码使用localhost工作正常,但我无法弄清楚客户端如何实际连接到服务器主机,以便它查找rmiregistry。我对存储在服务器的注册表中的内容感到困惑,是Sample还是localhost?这可能是愚蠢但我试图将localhost转换为客户端的ipaddress并执行String url =“//”+ server +“:”+ 1099 +“/ Sample”;其中server是来自getbyname()的ip,但我得到一个异常:java.rmi.NotBoundException:127.0.0.1:1099 / Sample 那是两台机器上的客户端和服务器。我只想弄清楚两者是如何远程连接的,但它甚至不能使用localhost的ip地址在同一台机器上工作。

客户端:

 import java.net.InetAddress;
import java.rmi.Naming;
import java.rmi.RemoteException;

public class SampleClient  {
    public static void main(String args[]) {



            String url = "//" + "localhost" + ":" + 1099 + "/Sample";

            SampleInterface sample = (SampleInterface)Naming.lookup(url);



        } catch(Exception e) {
            System.out.println("SampleClient exception: " + e);
        }
    }
}

服务器:

  import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.RMISecurityManager;
import java.rmi.server.UnicastRemoteObject;

public class SampleServer {
    public static void main(String args[]) throws IOException {

        // Create and install a security manager
        if (System.getSecurityManager() == null)
            System.setSecurityManager(new RMISecurityManager());
        try {

            String url = "//localhost:" + 1099 + "/Sample";
            System.out.println("binding " + url);
            Naming.rebind(url, new Sample());
            // Naming.rebind("Sample", new Sample());
            System.out.println("server " + url + " is running...");
        }
        catch (Exception e) {
            System.out.println("Sample server failed:" + e.getMessage());
        }
    }
}

1 个答案:

答案 0 :(得分:1)

服务器应绑定到在“localhost”上运行的注册表。

客户端应在服务器主机上查找注册表。

就这么简单。

  

我对存储在服务器的注册表中的内容感到困惑,是Sample还是localhost?

都不是。你混淆了三件不同的事情:

  1. 主机名,在本例中为“localhost”。
  2. 绑定名称,在本例中为“Sample”。
  3. 绑定的对象,即远程存根。
相关问题