简介:
一个简单的基于RMI的测试,RMI(Remote Method Invocation)
即 Java
远程方法调用,RMI
用于构建分布式应用程序,RMI
实现了 Java
程序之间跨 JVM
的远程通信。
一、客户端服务端都定义ClassDefine
public interface HelloDefine extends Remote {
public String helloWorld() throws RemoteException;
public String sayHello(String name) throws RemoteException;
}
二、在服务端实现ClassDe
public class HelloDefineImp extends UnicastRemoteObject implements HelloDefine {
private static final long serivalVersionUID = 1L;
public HelloDefineImp() throws RemoteException{
super();
}
public String helloWorld() throws RemoteException{
return "Hello AlphaGo!";
}
public String sayHello(String name) throws RemoteException{
return "Hello "+ name +" !";
}
}
三、服务端配置
本地配置:
public class HelloServer {
HelloDefine hello;
public void server() throws RemoteException, MalformedURLException, AlreadyBoundException{
hello = new HelloDefineImp();
//远程对象注册实例
LocateRegistry.createRegistry(8080);
//bind绑定链接本地的URL
Naming.bind("rmi://localhost:8080/Hello",hello);//本地
System.out.println("server:对象绑定成功!");
}
}
远程配置:
因为Naming只能在本地用,用远程要用到Registry类。
public class HelloServer {
HelloDefine hello;
public void server() throws RemoteException, MalformedURLException, AlreadyBoundException{
hello = new HelloDefineImp();
Registry registry = LocateRegistry.createRegistry(8080);//在RMIServer上创建
registry.rebind("HelloServer", hello); //HelloServer就是对外暴露出的名称</span></span>
System.out.println("server:对象绑定成功!");
}
}
四、客户端配置:
本地配置:
public class HelloClient {
public HelloDefine hello;
public void client() throws MalformedURLException, RemoteException, NotBoundException{
hello = (HelloDefine) Naming.lookup("rmi://localhost:8080/Hello");
//
System.out.println("client:");
System.out.println(hello.helloWorld());
System.out.println(hello.sayHello("RhichardChan"));
}
}
远程配置:
public class HelloClient {
public HelloDefine hello;
public void client() throws MalformedURLException, RemoteException, NotBoundException{
String hostName = "192.168.1.101";
int port = 8080;
Registry registry=LocateRegistry.getRegistry(hostName,port);
hello = (HelloDefine) registry.lookup( "HelloServer");
System.out.println("client:");
System.out.println(hello.helloWorld());
System.out.println(hello.sayHello("RhichardChan"));
}
}
五、测试
1、服务端运行:
public class RmiTest {
@Test
public void testServer() throws RemoteException, MalformedURLException, AlreadyBoundException{
HelloServer server = new HelloServer();
server.server();
while (true);
}
}
服务器Running:
2、客户端运行:
public class RmiTest {
@Test
public void testClient() throws MalformedURLException,RemoteException, NotBoundException{
HelloClient client = new HelloClient();
client.client();
}
}
客户端实现: