public classSimpleServer {private Map remoteObjects = new HashMap<>();//把一个远程对象放入到缓存中
public voidregister(String className,Object
remoteObject){
remoteObjects.put(className, remoteObject);
}public void service() throwsException{
ServerSocket serverSocket= newServerSocket(8088);
System.out.println("服务启动");while(true){
Socket socket=serverSocket.accept
();
InputStream in=socket.getInputStream();
ObjectInputStream ois= newObjectInputStream(in);
OutputStream out=socket.getOutputStream();
ObjectOutputStream oos= newObjectOutputStream(out);
Call call=(Call) ois.readObject
();//接收客户端发送的call对象
System.out.println(call);
call= invoke(call);//调用相关对象的
方法
oos.writeObject(call);//向客户端发送
包含了执行结果的Call对象
ois.close();
oos.close();
socket.close();
}
}publicCall invoke(Call 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 newException
(className+ "的远程对象不存在");
}else{
result=method.invoke
(remoteObject, params);
}
}catch(Exception e) {
result=e;
}
call.setResult(result);returncall;
}public static void main(String[] args) throwsException {
SimpleServer server= newSimpleServer();//把事先创建的HelloServiceImpl对象加入到服务器
的缓存中,//"com.lazy.socket.reflect.HelloService"类的
全限定名
server.register
("com.lazy.socket.reflect.HelloService", newHelloServiceImpl());
server.service();
}
}