涉及类:
ObjectInputStream
ObjectOutputStream
作用:可以从底层流中读取和写入对象类型的数据。包装流对象。即可在TCP服务器和客户端之间传递数据
DEMO:
import java.io.Serializable;
//实体类 需要继承Serializable接口
class Student implements Serializable{
int id;
String name;
int age;
String department;
public Student(int id,String name,int age,String department){
this.id=id;
this.name=name;
this.age=age;
this.department=department;
}
}
import java.net.*;
import java.io.*;
//服务器端程序
class ObjectServer
{
public static void main(String[] args) throws Exception
{
ServerSocket ss=new ServerSocket(8001);
Socket s=ss.accept();
OutputStream ops=s.getOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(ops);//构建底层输出流
Student stu=new Student(1,"xingming",25,"music");
oos.writeObject(stu);//将对象写入
oos.close();
s.close();
ss.close();
}
}
import java.net.*;
import java.io.*;
//客户端程序
class ObjectClient
{
public static void main(String[] args) throws Exception
{
Socket s=new Socket("127.0.0.1",8001);
InputStream ips=s.getInputStream();
ObjectInputStream ois=new ObjectInputStream(ips);//构建读取对象的输入流
Student stu=(Student)ois.readObject();
System.out.println("id is "+stu.id);
System.out.println("name is "+stu.name);
System.out.println("age is "+stu.age);
System.out.println("department is "+stu.department);
ois.close();
s.close();
}
}