Java远程调用原理DEMO
1. POJO
public class DemoInfo implements Serializable{ private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "DemoInfo{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
2. Service接口定义
public interface IDemoService { DemoInfo getDemoInfoById(DemoInfo info); }
3. Provider服务实现
public class DemoServiceImpl implements IDemoService{ @Override public DemoInfo getDemoInfoById(DemoInfo info) { System.out.println(info); DemoInfo demoInfo = new DemoInfo(); demoInfo.setName("zhangsan"); demoInfo.setAge(20); return demoInfo; } }
4. Provider
public class Provider { public static void main(String[] args) { ServerSocket server = null; try { server = new ServerSocket(5678); while (true) { Socket socket = server.accept(); ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); DemoInfo info = (DemoInfo) ois.readObject(); socket.shutdownInput(); IDemoService service = new DemoServiceImpl(); DemoInfo retInfo = service.getDemoInfoById(info); ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); oos.writeObject(retInfo); oos.flush(); socket.shutdownOutput(); socket.close(); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { try { if (server != null) { server.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
5. Consumer
public class Consumer { public static void main(String[] args) { IDemoService service = (IDemoService) Proxy.newProxyInstance(IDemoService.class.getClassLoader(), new Class[]{IDemoService.class}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Socket socket = new Socket("192.168.1.1",5678); ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); oos.writeObject(args[0]); oos.flush(); socket.shutdownOutput(); ObjectInputStream ios = new ObjectInputStream(socket.getInputStream()); DemoInfo retInfo = (DemoInfo)ios.readObject(); socket.shutdownInput(); System.out.println(retInfo); return null; } }); DemoInfo info = new DemoInfo(); info.setName("lisi"); info.setAge(18); service.getDemoInfoById(info); } }
点亮测试人生!QQ:408129370
百度阅读电子书地址:http://yuedu.baidu.com/ebook/f6dbb2a2f01dc281e53af0f3
讨论QQ群:536192476
个人公众号:
百度阅读电子书地址:http://yuedu.baidu.com/ebook/f6dbb2a2f01dc281e53af0f3
讨论QQ群:536192476
个人公众号: