服务器端代码:
public class Server {
//存放远程对象的缓存
private Map remoteObjects = new HashMap();
//注册服务:把一个远程对象放到缓存中
public void register(String className, Object remoteObject) {
remoteObjects.put(className, remoteObject);
}
public void service() throws Exception {//创建基于流的socket,并在8000端口监听
ServerSocket serverSocket = new ServerSocket(8001);
System.out.println("服务器启动...");
Socket socket = serverSocket.accept();
InputStream in = socket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(in);
OutputStream out = socket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(out);
//接收客户端发送的Call对象
RemoteCall remoteCallObj = (RemoteCall) ois.readObject();
System.out.println(remoteCallObj);
//调用相关对象的方法
remoteCallObj = invoke(remoteCallObj);
//向客户发送包含执行结果的remoteCallObj对象
oos.writeObject(remoteCallObj);
System.out.println(remoteCallObj.getResult());
ois.close();
oos.close();
socket.close();
}
public RemoteCall invoke(RemoteCall call) {
Object result = null;
try {
String className = call.getClassName();
String methodName = call.getMethodName();
Object[] params = call.getParams();
Class classType = Class.forName(className);
Class[] paramTypes = call.getParamTypes();
Method method = classType.getMethod(methodName, paramTypes);
//从缓存中取出相关的远程对象
Object remoteObject = remoteObjects.get(className);
if(remoteObject == null) {
throw new Exception(className + "的远程对象不存在");
}else {
result = method.invoke(remoteObject, params);
}
}catch(Exception e) {
result = e;
}
call.setResult(result);
return call;
}
}
客户端代码为:
public class RemoteClient {
public void invoke() throws Exception{
Socket socket = new Socket("localhost",8001);
OutputStream out = socket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(out);
RemoteCall call = new RemoteCall("com.interfaces.RPCService", "getInformation",
new Class[] {String.class},new Object[]{"测试RPC!"});
//向服务器发送Call对象
oos.writeObject(call);
//接收包含了方法执行结果的Call对象
InputStream in = socket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(in);
call = (RemoteCall)ois.readObject();
System.out.println(call.getResult());
ois.close();
oos.close();
socket.close();
}
public static void main(String args[]) throws Exception{
new RemoteClient().invoke();
}
}
图片描述