简体   繁体   中英

connecting client-server RMI

I am confused on how the client actually makes the connection to the server if the server is remote(not on the same machine as the client). My code works fine using localhost but i cant figure out how the client actually makes the connection to the server host so that it looks up the rmiregistry. I'm confused on what gets stored in the registry for the server, is it Sample or localhost? This may be dumb but i tried to convert localhost to its ipaddress on the client side and do String url = "//" + server + ":" + 1099 + "/Sample"; where server is the ip from getbyname() but i get a exception: java.rmi.NotBoundException: 127.0.0.1:1099/Sample That was with the client and server on both machines. I'm just trying to figure out how the two connect remotely but it didn't even work on the same machine using the ip address of localhost.

Client:

 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);
        }
    }
}

Server:

  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());
        }
    }
}

The server should bind to a Registry running on 'localhost'.

The client should lookup a Registry at the server host.

It's as simple as that.

I'm confused on what gets stored in the registry for the server, is it Sample or localhost?

Neither. You're confusing three different things:

  1. The hostname, in this case 'localhost'.
  2. The bind-name, in this case 'Sample'.
  3. The object which is bound, which is the remote stub.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM