- 返回值一定是一个对象,当前是把user拆分成1个id,1个name返回,当user变了,比如增加了属性,则需要再次修改相应代码,因此需要进一步优化
- 直接将这个对象返回,不进行拆分
- Stub:返回值封装成Object对象
package com.bill.rpc05;
import com.bill.rpc.common.IUserService;
import com.bill.rpc.common.User;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;
/**
* @Auther: wangchunwen
* @Date: 2023/1/5 - 01 - 05 - 23:15
* @Description: com.bill.rpc05
* @version: 1.0
*/
public class Stub {
public static IUserService getStub(){
InvocationHandler h = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Socket s = new Socket("127.0.0.1",8888);
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
String methodName = method.getName();
Class[] parametersTypes = method.getParameterTypes();
oos.writeUTF(methodName);
oos.writeObject(parametersTypes);
oos.writeObject(args);
oos.flush();
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
User user = (User) ois.readObject();
oos.close();
s.close();
return user;
}
};
Object o = Proxy.newProxyInstance(IUserService.class.getClassLoader(),new Class[] {IUserService.class},h);
System.out.println(o.getClass().getName());
System.out.println(o.getClass().getInterfaces()[0]);
return (IUserService)o;
}
}
- server
package com.bill.rpc05;
import com.bill.rpc.common.IUserService;
import com.bill.rpc.common.User;
import com.bill.rpc01.UserServiceImpl;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @Auther: wangchunwen
* @Date: 2023/1/5 - 01 - 05 - 23:14
* @Description: com.bill.rpc05
* @version: 1.0
*/
public class Server {
private static boolean running = true;
public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
ServerSocket ss = new ServerSocket(8888);
while (running){
Socket s = ss.accept();
process(s);
s.close();
}
ss.close();
}
private static void process(Socket s) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
ObjectInputStream ois = new ObjectInputStream(in);
String methodName = ois.readUTF();
Class[] parameterTypes = (Class[]) ois.readObject();
Object[] args = (Object[]) ois.readObject();
IUserService service = new UserServiceImpl();
Method method = service.getClass().getMethod(methodName,parameterTypes);
User user = (User) method.invoke(service,args);
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(user);
oos.flush();
}
}
标签:java,05,bill,230105,RPC,oos,new,import,com
From: https://www.cnblogs.com/wcwblog/p/17029146.html