浅谈JAVA-RMI serverdemo: package com.ray.rmi;import java.rmi.Naming;import java.rmi.Remote;import java.rmi.RemoteException;import java.rmi.registry.LocateRegistry;import java.rmi.server.UnicastRemoteObject;public class RMIServer { public
serverdemo:
package com.ray.rmi;
import java.rmi.Naming;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;
public class RMIServer {
public interface IRemoteHelloWorld extends Remote {
public String hello() throws RemoteException;
}
public class RemoteHelloWorld extends UnicastRemoteObject implements
IRemoteHelloWorld {
protected RemoteHelloWorld() throws RemoteException {
super();
}
public String hello() throws RemoteException {
System.out.println("call from");
return "Hello world";
}
}
private void start() throws Exception {
RemoteHelloWorld h = new RemoteHelloWorld();
LocateRegistry.createRegistry(1099);
Naming.rebind("Hello", h);
}
public static void main(String[] args) throws Exception {
new RMIServer().start();
}
}
\1. ⼀一个继承了了 java.rmi.Remote 的接⼝口,其中定义我们要远程调⽤用的函数,⽐比如这⾥里里的 hello()
\2. ⼀一个实现了了此接⼝口的类
\3. ⼀一个主类,⽤用来创建Registry,并将上⾯面的类实例例化后绑定到⼀一个地址。这就是我们所谓的Server
了了。
client:
package com.ray.rmi;
import java.rmi.Naming;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;
public class RMIServer {
public interface IRemoteHelloWorld extends Remote {
public String hello() throws RemoteException;
}
public class RemoteHelloWorld extends UnicastRemoteObject implements
IRemoteHelloWorld {
protected RemoteHelloWorld() throws RemoteException {
super();
}
public String hello() throws RemoteException {
System.out.println("call from");
return "Hello world";
}
}
private void start() throws Exception {
RemoteHelloWorld h = new RemoteHelloWorld();
LocateRegistry.createRegistry(1099);
Naming.rebind("Hello", h);
}
public static void main(String[] args) throws Exception {
new RMIServer().start();
}
}
客户端就简单多了了,使⽤用 Naming.lookup 在Registry中寻找到名字是Hello的对象,后⾯面的使⽤用就和在
本地使⽤用⼀一样了了。
虽说执⾏行行远程⽅方法的时候代码是在远程服务器器上执⾏行行的,但实际上我们还是需要知道有哪些⽅方法,这时
候接⼝口的重要性就体现了了,这也是为什什么我们前⾯面要继承 Remote 并将我们需要调⽤用的⽅方法写在接⼝口
IRemoteHelloWorld ⾥里里,因为客户端也需要⽤用到这个接口。
效果: