码迷,mamicode.com
首页 > 编程语言 > 详细

java RMI

时间:2016-04-14 10:37:41      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:

 

 

import java.rmi.*;

public interface Hello extends Remote {
    public String getGreeting() throws RemoteException;
}

 

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

public class HelloImpl extends UnicastRemoteObject implements Hello {
    
    public HelloImpl() throws RemoteException {
        // No action needed here.
    }

    public String getGreeting() throws RemoteException {
        return ("Hello there!");
    }
}

 

import java.rmi.*;

public class HelloServer {
    private static final String HOST = "localhost";

    public static void main(String[] args) throws Exception {
        // Create a reference to an
        // implementation object
        HelloImpl temp = new HelloImpl();
        // Create the string URL holding the
        // object‘s name
        String rmiObjectName = "rmi://" + HOST + "/Hello";
        // (Could omit host name here, since ‘localhost‘
        // would be assumed by default.)
        // ‘Bind‘ the object reference to the name
        Naming.rebind(rmiObjectName, temp);
        // Display a message so that we know the process
        // has been completed
        System.out.println("Binding complete…\n");
    }
}

 

import java.rmi.*;

public class HelloClient {
    private static final String HOST = "localhost";

    public static void main(String[] args) {
        try {
            // Obtain a reference to the object from the
            // registry and typecast it into the appropriate
            // type
            Hello greeting = (Hello) Naming.lookup("rmi://" + HOST + "/Hello");
            // Use the above reference to invoke the remote
            // object‘s method
            System.out.println("Message received: " + greeting.getGreeting());
        } catch (ConnectException conEx) {
            System.out.println("Unable to connect to server!");
            System.exit(1);
        } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(1);
        }
    }
}

 

编译运行用到的命令

note

javac Hello.java
javac HelloImpl.java
javac HelloServer.java
javac HelloClient.java

//This would generate both a stub fi le and a skeleton fi le. However, this stage is no
//longer required
rmic HelloImpl

//Starting the RMI registry
rmiregistry

//start server
java HelloServer

//start client
java HelloClient


//result
"Hello there!"

 

java RMI

标签:

原文地址:http://www.cnblogs.com/rojas/p/5390111.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!