Java RMI简单使用

服务端代码

远程服务接口(MyRemoteService.java)

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

public interface MyRemoteService extends Remote {
	public String sayHello() throws RemoteException;
}

远程服务接口实现(MyRemoteServiceImpl.java)

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class MyRemoteServiceImpl extends UnicastRemoteObject implements MyRemoteService {
	private static final long serialVersionUID = -1277417111394467757L;

	protected MyRemoteServiceImpl() throws RemoteException {
		super();// 必须有构造器抛出RemoteException异常
	}

	@Override
	public String sayHello() throws RemoteException {
		return "Server says hello!";
	}
}

启动远程服务代码(Server.java)

import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;

public class Server {
	public static void main(String[] args) {
		try {
			MyRemoteService service = new MyRemoteServiceImpl();
			LocateRegistry.createRegistry(12345);
			Naming.rebind("rmi://localhost:12345/RemoteHello", service);// 绑定本地rmiregistry端口
			System.out.println("servier running");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

客户端代码(Client.java)

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

public class Client {
	public static void main(String[] args) {
		try {
			MyRemoteService myRemote = (MyRemoteService) Naming.lookup("rmi://localhost:12345/RemoteHello");
			String s = myRemote.sayHello();
			System.out.println(s);
		} catch (MalformedURLException | RemoteException | NotBoundException e) {
			e.printStackTrace();
		}
	}
}

编译代码,启动Server和Client

javac *.java
java Server
java Client

可以看到输出

你可能感兴趣的:(Java,RMI)