任务三:传输对象输入与输出流
现有一个Student类;
- 程序实现:从服务器端传输一个Student对象到客户端,客户端输出该对象信息。
- 基本要求:使用Socket类和ServerSocket类实现。
package third;
import java.io.Serializable;
public class Student implements Cloneable,Serializable{
private int id;
private String name;
private int age;
public Student() {
}
public Student(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
// toString()
public String toString() {
return "Student [id=" + id +
", name="+ name +
", age="+ age + "]";
}
}
package third;
import java.io.*;
import java.net.*;
public class Server {
public static void main(String args[]) {
Student s1 = new Student(1001, "Lee", 21);
Student s2 = new Student(1003, "Zhang", 22);
ServerSocket server=null;
Socket you=null;
DataOutputStream out=null;
DataInputStream in=null;
try { server=new ServerSocket(4322);
}
catch(IOException e1) {
System.out.println(e1);
}
try{ System.out.println("等待客户呼叫");
you=server.accept(); //堵塞状态,除非有客户呼叫
System.out.println("等待客户呼叫");
out=new DataOutputStream(you.getOutputStream());
in=new DataInputStream(you.getInputStream());
ObjectOutputStream ofs = new ObjectOutputStream(out);
ofs.writeObject(s1);
ofs.writeObject(s2);
ofs.close();
}
catch(Exception e) {
System.out.println("客户已断开"+e);
}
}
}
package third;
import java.io.*;
import java.net.*;
public class Client {
public static void main(String args[]) {
Socket mysocket;
DataInputStream in=null;
DataOutputStream out=null;
try{ mysocket=new Socket("127.0.1.1",4322);
in=new DataInputStream(mysocket.getInputStream());
out=new DataOutputStream(mysocket.getOutputStream());
ObjectInputStream ifs = new ObjectInputStream(in);
Student s3 = new Student();
s3 = (Student)ifs.readObject();
System.out.println(s3.toString());
s3 = (Student)ifs.readObject();
System.out.println(s3.toString());
ifs.close();
}
catch(Exception e) {
System.out.println("服务器已断开"+e);
}
}
}



