合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
利用对象流互发信息 Test6.java ~~~ package chat.a4; import java.io.*; import java.net.*; public class Test6 { public static void main(String[] args) { Test6 t=new Test6(); } public Test6(){ try { ServerSocket ss=new ServerSocket(9999); Socket s=ss.accept(); ObjectInputStream ois=new ObjectInputStream(s.getInputStream()); User u=(User)ois.readObject(); System.out.println(u.getName()); System.out.println(u.getPass()); } catch (Exception e) { // TODO: handle exception } } } ~~~ Test7.java ~~~ package chat.a4; import java.io.*; import java.net.*; public class Test7 { public static void main(String[] args) { Test7 t=new Test7(); } public Test7(){ try { Socket s=new Socket("127.0.0.1",9999); ObjectOutputStream oos=new ObjectOutputStream(s.getOutputStream()); User u = new User(); u.setName("张三"); u.setPass("123"); oos.writeObject(u); oos.close();//关闭对象流 } catch (Exception e) { // TODO: handle exception } } } ~~~ User.java ~~~ package chat.a4; import java.io.Serializable; public class User implements Serializable{//将user序列化 private String name; private String pass; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } } ~~~ 结果: ![](https://box.kancloud.cn/5ae2ab553cb60523460e3e7742a48edf_801x201.png)