RMI简单例子

来源:互联网 发布:主机公园 php搭建 编辑:程序博客网 时间:2024/05/16 18:21
1)定义一个接口
public interface HelloInterface extends Remote{
     public String sayHello(String name) throws RemoteException; 
}

2)实现接口
public class HelloInterfaceImpl extends UnicastRemoteObject implements HelloInterface{
    protected HelloInterfaceImpl() throws RemoteException {
    }
    public String sayHello(String name) throws RemoteException {
        String strHello = "你 " + name+" 欢器";
        System.out.println(name +" 正 ");
                return strHello;
    }} 


3)启动 server
            HelloInterface hInterface = new HelloInterfaceImpl();
            int port = 6666
            LocateRegistry.createRegistry(port);
            String address = "rmi://localhost:" + port + "/hello";
            System.out.println("服务端地址: "+address);
            Naming.bind(address,hInterface);
            System.out.println(">>>服务端成功启动");


4)启动client
        int port = 6666;
        String address = "rmi://127.0.0.1:" + port + "/hello"; 
        try {
        HelloInterface hInterface = (HelloInterface) Naming.lookup(address);
            System.out.println("客户端成功启动");
            System.out.println(hInterface.sayHello("aaaa")); 
        } catch (MalformedURLException e) { 
原创粉丝点击