服务端 :
HelloService
public interface HelloService { public String hello(String name); }
HelloServiceImpl
public class HelloServiceImpl implements HelloService { @Override public String hello(String name) { return "Hello " + name; } }
RPCServer
public class RPCServer { private ExecutorService threadPool; private static final int DEFAULT_THREAD_NUM = 10; public RPCServer() { this.threadPool = Executors.newFixedThreadPool(DEFAULT_THREAD_NUM); } public void register(Object service, int port){ try { System.out.println("server start..."); ServerSocket server = new ServerSocket(port); Socket socket = null; while ((socket = server.accept()) != null){ System.out.println("client connected.."); threadPool.execute(new Processor(socket, service)); } }catch (IOException e){ e.printStackTrace(); } } class Processor implements Runnable{ Socket socket; Object service; public Processor(Socket socket, Object service) { this.socket = socket; this.service = service; } public void process(){ } @Override public void run() { try { ObjectInputStream in = new ObjectInputStream(socket.getInputStream()); String methodName = in.readUTF(); Class<?>[] paramterTypes = (Class<?>[]) in.readObject(); Object[] parameters = (Object[]) in.readObject(); Method method = service.getClass().getMethod(methodName, paramterTypes); try { Object result = method.invoke(service, parameters); ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); out.writeObject(result); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } }
ServerTest
public class ServerTest { public static void main(String[] args) { HelloService helloService = new HelloServiceImpl(); RPCServer server = new RPCServer(); server.register(helloService, 50001); } }
------------------------------------------------------------------------------------------------------------------------
客户端:
public class RPCClientTest { public static void main(String[] args) { HelloService helloService = getClient(HelloService.class, "127.0.0.1", 50001); System.out.println(helloService.hello("saxing")); } @SuppressWarnings("unchecked") public static <T> T getClient(Class<T> clazz, final String ip, final int port){ return (T) Proxy.newProxyInstance(RPCClientTest.class.getClassLoader(), new Class<?>[]{clazz}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Socket socket = new Socket(ip, port); ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); out.writeUTF(method.getName()); out.writeObject(method.getParameterTypes()); out.writeObject(args); ObjectInputStream in = new ObjectInputStream(socket.getInputStream()); return in.readObject(); } }); } }