rmi入门(带源码)

大体上分为如下几步
  • 定义接口
  • 服务端编写实现
  • 编写客户端
  • 编写运行脚本

1、定义接口
public interface ServerIntf extends Remote {
	String sayHello() throws RemoteException;
}

2、编写实现类
public class Server implements ServerIntf {

	public Server() {
	}

	public String sayHello() {
		System.err.println("Hello, world!");
		return "Hello, world!";
	}

	public static void main(String args[]) {

		try {
			Server obj = new Server();
			ServerIntf stub = (ServerIntf) UnicastRemoteObject.exportObject(obj, 0);

			// Bind the remote object's stub in the registry
			Registry registry = LocateRegistry.getRegistry(2001);
			registry.bind("Hello", stub);

			System.err.println("Server ready");
		} catch (Exception e) {
			System.err.println("Server exception: " + e.toString());
			e.printStackTrace();
		}
	}
}

3、编写客户端
public class Client  {

    private Client() {}

    public static void main(String[] args) {

	String host = (args.length < 1) ? null : args[0];
	try {
	    Registry registry = LocateRegistry.getRegistry(host, 2001);
	    ServerIntf stub = (ServerIntf) registry.lookup("Hello");
	    String response = stub.sayHello();
	    System.out.println("response: " + response);
	} catch (Exception e) {
	    System.err.println("Client exception: " + e.toString());
	    e.printStackTrace();
	}
    }
}

4、编写运行脚本(包括生成存根和rmi注册)
rem 生成存根
rmic com.talent.rmi.server.Server

rem 必须先设置路径再进行rmi注册
set CLASSPATH=%CLASSPATH%;.\
start rmiregistry 2001

rem 启动服务器
java com.talent.rmi.server.Server

附件包中包括以上几步的所有内容,可能直接使用

你可能感兴趣的:(java,脚本)