JavaEE(3)

1. 开发RMI服务器

Net Beans创建java project: (qs) (Server.java)

package server;

import java.rmi.*;

//远程接口必须集成java.rmi.Remote接口
public interface Server extends Remote 
{
    //所有在Remote接口里声明的方法都应该抛出RemoteException异常
    String helloWorld(String name) throws RemoteException;
    Person getPerson(String name , int age) throws RemoteException;
}

Person.java

package server;

import java.io.*;

public class Person implements Serializable {

    private String name;
    private int age;

    //无参数的构造器
    public Person() {
    }

    //初始化全部属性的构造器
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    //name属性的setter和getter方法
    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    //age属性的setter和getter方法
    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return this.age;
    }
}
View Code

ServerImpl.java

package server;

import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;
import javax.naming.*;

//远程服务类,远程服务类必须继承UnicastRemoteObject,并实现Remote接口
public class ServerImpl extends UnicastRemoteObject implements Server
{
    //由于默认构造器必须声明抛出RemoteException
    //因此此处必须显式定义该构造器
    public ServerImpl() throws RemoteException
    {
    }
    //实现Remote接口必须实现的方法
    public String helloWorld(String name) throws RemoteException
    {
        return name + ", 您好!";
    }
    //实现Remote接口必须实现的方法
    public Person getPerson(String name , int age) throws RemoteException
    {
        return new Person(name , age);
    }
    //下面是服务类的本地方法,不会“暴露”为远程服务。
    public void info()
    {
        System.out.println("我是本地方法");
    }
    //下面提供程序入口,将远程类实例绑定为本机的服务。
    public static void main(String[] args) throws Exception
    {
        //创建远程服务类实例
        Server imp = new ServerImpl();
        //注册远程服务的端口
        LocateRegistry.createRegistry(1099);
        //将远程服务实例绑定为远程服务。
        Naming.rebind("rmi://:1099/crazyit", imp);
    }
}

2. 开发RMI客户端

需要RMI服务端的Server.clsss和Person.class

RMIClient.java

package client;

import javax.naming.*;
import java.rmi.*;
import server.Server;

public class RMIClient
{
    public static void main(String[] args)throws Exception
    {
        //通过JNDI查找远程服务,并执行强制类型转换
        Server ser = (Server)Naming.lookup("rmi://127.0.0.1:1099/crazyit");
        System.out.println(ser instanceof java.rmi.server.RemoteStub);
        //调用远程方法
        System.out.println(ser.helloWorld("yeeku"));
        //调用远程方法。
        System.out.println(ser.getPerson("yeeku",28));
    }
}
原文地址:https://www.cnblogs.com/thlzhf/p/4248974.html