RMI之HelloWorld尝试

服务器端代码如下:

IHello接口:

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface IHello extends Remote { 

    /** 
     * @return return hellowold
     * @throws java.rmi.RemoteException 
     */ 
    public String helloWorld() throws RemoteException; 

    /** 
     * @param someBodyName
     * @return say hello to somebody 
     * @throws java.rmi.RemoteException 
     */ 
    public String sayHelloToSomeBody(String someBodyName) throws RemoteException; 
}

Hello实现:

import java.net.MalformedURLException;
import java.rmi.AlreadyBoundException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;

/**
 * @ClassName: HelloImpl
 * @Description: TODO
 * @author: Dorothy
 * @Date: 2014-12-21 00:00:13
 */
public class HelloImpl  extends UnicastRemoteObject implements IHello { 
    /** 
     * 
     * @throws RemoteException 
     */ 
    public HelloImpl() throws RemoteException { 
    } 

    /** 
     * 
     * @return return Hello World!
     * @throws java.rmi.RemoteException 
     */ 
    public String helloWorld() throws RemoteException { 
        return "Hello World!"; 
    } 

    /** 
     * 
     * @param someBodyName  
     * @return say Hello to somebody
     * @throws java.rmi.RemoteException 
     */ 
    public String sayHelloToSomeBody(String someBodyName) throws RemoteException { 
        return "Hello " + someBodyName + "!"; 
    } 
    
    
    public static void main(String args[]) { 

        try { 
            
            IHello rhello = new HelloImpl(); 
            LocateRegistry.createRegistry(8888);
            Naming.bind("rmi://localhost:8888/RHello",rhello);

            System.out.println(">>>>>INFO:Binding Successfully!"); 
        } catch (RemoteException e) { 
            e.printStackTrace(); 
        } catch (AlreadyBoundException e) { 
            e.printStackTrace(); 
        } catch (MalformedURLException e) { 
            e.printStackTrace(); 
        }  
    } 
}

 

 

客户端代码如下:

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

/**
 * @ClassName: HelloClient
 * @Description: TODO
 * @author: Dorothy
 * @Date: 2014-12-21 00:06:08
 */
public class HelloClient {
    public static void main(String args[]){ 
        try { 
            IHello rhello =(IHello) Naming.lookup("rmi://localhost:8888/RHello"); 
            System.out.println(rhello.helloWorld()); 
            System.out.println(rhello.sayHelloToSomeBody("Dorothy")); 
        } catch (NotBoundException e) { 
            e.printStackTrace(); 
        } catch (MalformedURLException e) { 
            e.printStackTrace(); 
        } catch (RemoteException e) { 
            e.printStackTrace();   
        } 
    } 
}

同时IHello接口定义,在客户端也要有。

 

在linux机器之间测试通过,windows和linux之间不成功,以后有时间再看为什么~

posted @ 2014-12-21 15:34  dorothychai  阅读(228)  评论(0编辑  收藏  举报