在TCP网络连接上传递对象·ObjectInputStream和ObjectOutputStream可以从底层输入流中读取对象类型的数据和将对象类型的数据写入到底层输出流。·使用ObjectInputStream和ObjectOutputStream来包装底层网络字节流,TCP服务器和TCP客户端之间就可以传递对象类型的数据。·编程实例:通过网络传输Java对象。import java.net.*;import java.io.*;
public class ObjectServer { /** * Method main * * * @param args * */ public static void main(String[] args) throws Exception { // TODO: Add your code here ServerSocket ss = new ServerSocket(8001); Socket s = ss.accept(); OutputStream out = s.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(out); Student st = new Student(10,"zhangshan",30,"huaxue"); oos.writeObject(st); oos.close(); s.close(); ss.close(); } }import java.io.*;import java.net.*;
public class ObjectClient { /** * Method main * * * @param args * */ public static void main(String[] args) throws Exception{ // TODO: Add your code here Socket s = new Socket("127.0.0.1",8001); InputStream in = s.getInputStream(); ObjectInputStream ois = new ObjectInputStream(in); Student st = (Student)ois.readObject(); System.out.println (st); ois.close(); s.close(); } }import java.io.Serializable;
class Student implements Serializable { private int id; private String naem; private int age; private String department;
public Student(int id, String naem, int age, String department) { this.id = id; this.naem = naem; this.age = age; this.department = department; } //其它代码省略主要是geter、seter和toString方法}