import java.io.ObjectInputStream; import java.net.ServerSocket; import java.net.Socket; public class TcpService { public static void main(String args[]) throws Exception { ServerSocket ss = new ServerSocket(3000); Socket socket = ss.accept(); ObjectInputStream oos = new ObjectInputStream(socket.getInputStream()); Student stu = (Student) oos.readObject(); oos.close(); ss.close(); System.out.println(stu.getName() + "," + stu.getAge() + "," + stu.getSex()); } } import java.io.ObjectOutputStream; import java.net.Socket; public class TcpClients { public static void main(String[] args) throws Exception { Student stu1 = new Student("张三", 18, "男"); Socket socket = new Socket("127.0.0.1", 3000); ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); oos.writeObject(stu1); oos.close(); socket.close(); } } import java.io.Serializable; public class Student implements Serializable { public Student(String name, int age, String sex) { this.setName(name); this.setAge(age); this.setSex(sex); } private String name; private int age; private String sex; 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; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } } 运行结果: