Server-side code:
public class Server {
//
private Map remoteObjects = new HashMap();
//:
public void register(String className, Object remoteObject) {
remoteObjects.put(className, remoteObject);
}
public void service() throws Exception {//socket8000
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;
}
}
client code is:
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();
}
}
Picture description