RMI简单应用:
我决定秉承一贯直接、爽快作风,直接代码分析:
服务器端代码:
package rmi.server.i;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
* @ version 创建时间:2014-3-24 上午11:25:58
*
* @ author leicl
*
* 类说明:
* 服务器端方法,供客户端访问,需要注册
*
*/
public interface ServerFunctionI extends Remote{
public int add(int i, int j) throws RemoteException;
public int div(int i, int j) throws RemoteException;
}
package rmi.server.imp;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import rmi.server.i.ServerFunctionI;
/**
* @ version 创建时间:2014-3-24 上午11:28:16
*
* @ author leicl
*
* 类说明:
*
*/
public class ServerFunctionImp extends UnicastRemoteObject implements ServerFunctionI{
public ServerFunctionImp() throws RemoteException {
super();
}
private static final long serialVersionUID = -6669980253701448838L;
public int add(int i, int j) throws RemoteException {
// TODO Auto-generated method stub
return i+j;
}
public int div(int i, int j) throws RemoteException {
// TODO Auto-generated method stub
return i-j;
}
}
客户端调用:
package rmi.client;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.AlreadyBoundException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.RMIClientSocketFactory;
import java.rmi.server.RMIServerSocketFactory;
import rmi.server.i.ServerFunctionI;
import rmi.server.imp.ServerFunctionImp;
/**
* @ version 创建时间:2014-3-24 上午11:33:04
*
* @ author leicl
*
* 类说明:
*
*/
public class Client1 {
public static void main(String[] args) throws MalformedURLException,
RemoteException, AlreadyBoundException, NotBoundException {
ServerFunctionI s = new ServerFunctionImp();
Registry regist = LocateRegistry.createRegistry(2323,
new RMIClientSocketFactory() {
public Socket createSocket(String host, int port)
throws IOException {
Socket s = new Socket(host, port);
return s;
}
}, new RMIServerSocketFactory() {
public ServerSocket createServerSocket(int port)
throws IOException {
ServerSocket s = new ServerSocket(port);
return s;
}
});
regist.bind("server", s);
String[] list = Naming.list("rmi://127.0.0.1:2323");
for (int i = 0; i < list.length; i++) {
System.out.println(list[i]);
}
ServerFunctionI ser = (ServerFunctionI) Naming
.lookup("rmi://127.0.0.1:2323/server");
int add = ser.add(1, 1);
System.out.println(add);
}
}