//———————–华丽的分割线———————————
package app01; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.List; public class Server { public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InstantiationException { ServerSocket server = new ServerSocket(); server.bind(new InetSocketAddress(8089)); while(true){ Socket socket = server.accept(); InputStream is = socket.getInputStream(); ObjectInputStream ois = new ObjectInputStream(is); String className = ois.readUTF(); Class c = Class.forName(className); String methodName = ois.readUTF(); Class[] ps = (Class[]) ois.readObject();//参数类型 Method method = c.getMethod(methodName, ps); Object[] arguments = (Object[]) ois.readObject();//参数 String ms = null; try { ms = (String) method.invoke(c.newInstance(), arguments); ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); oos.writeObject(ms); oos.flush(); oos.close(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } }//—————不太华丽的分割线————————
package app01; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.InetSocketAddress; import java.net.Socket; import java.util.ArrayList; import java.util.List; public class Client <T>{ public static void main(String[] args) throws ClassNotFoundException, IOException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException { RpcGetMes("app01.Didi", "getAddress", new Class[]{String.class, int.class}, new Object[]{"回龙观东大街", 8}); } static void RpcGetMes(String className, String methodName, Class[] ps, Object[] paras)throws IOException, ClassNotFoundException{ Socket socket = new Socket(); socket.connect(new InetSocketAddress("localhost", 8089)); OutputStream os = socket.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(os); oos.writeUTF(className); oos.writeUTF(methodName); oos.writeObject(ps); oos.writeObject(paras); oos.flush(); ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); String reMes = (String) ois.readObject(); System.out.println("客户端收到数据: " + reMes); oos.close(); } }