实现代码:
Student.java文件代码:
import java.io.*;
public class Student implements Serializable{
int id;
String name;
int age;
String department;
public Student(int id,String name,int age,String department) {
// TODO Auto-generated constructor stub
this.id = id;
this.name = name;
this.age = age;
this.department = department;
}
}
ObjectServer.java文件代码:
import java.net.*;
import java.io.*;
public class ObjectServer {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
ServerSocket ss = new ServerSocket(8001);
Socket s = ss.accept();
OutputStream ops = s.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(ops);
Student stu = new Student(19, "wangwu", 22, "huaxue");
oos.writeObject(stu);
oos.close();
s.close();
ss.close();
}
}
ObjectClient.java文件代码:
import java.io.*;
import java.net.*;
public class ObjectClient {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
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("deparment is " + stu.department);
ois.close();
s.close();
}
}
先运行ObjectServer程序之后再运行ObjectClient程序,ObjectClient程序会收到ObjectServer程序发来的stu对象。结果如下图: