彻底剖析RMI底层源码 、手写轻量级RMI框架
https://blog.csdn.net/Z0157/article/details/82049975
User
public class User { private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
UserClient
public class UserClient { public static void main(String[] args) throws IOException { User user = new UserStub(); int age = user.getAge(); System.out.println("age="+age); } }
UserServer
public class UserServer extends User { public static void main(String[] args) { UserServer userServer = new UserServer(); userServer.setAge(18); UserSkeleton userSkeleton = new UserSkeleton(userServer); userSkeleton.start(); } }
UserSkeleton
public class UserSkeleton extends Thread{ private UserServer userServer; public UserSkeleton(UserServer userServer){ this.userServer = userServer; } public void run(){ ServerSocket serverSocket =null; try { serverSocket = new ServerSocket(8888); Socket socket = serverSocket.accept(); while (socket !=null){ ObjectInputStream read = new ObjectInputStream(socket.getInputStream()); String method = (String) read.readObject(); System.out.println("server get data:"+method); if(method.equals("age")){ int age = userServer.getAge(); System.out.println("server set data:"+age); ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream()); outputStream.writeInt(age); outputStream.flush(); } } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); }finally { if (serverSocket !=null){ try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
UserStu
public class UserStub extends User { private Socket socket; public UserStub() throws IOException { socket = new Socket("localhost",8888); } public int getAge(){ try { ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream()); outputStream.writeObject("age"); System.out.println("client set data"); outputStream.flush(); ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream()); System.out.println("client read data start"); int age = objectInputStream.readInt(); System.out.println("client read data:"+age); return age; } catch (IOException e) { e.printStackTrace(); } return 0; } }