使用tcp传递对象
客户端代码如下:
import java.net.*; import java.io.*; public class ObjectClient { public static void main(String[] args) { try { Socket s = new Socket("127.0.0.1", 8001); // 实际编程不要写死 InputStream is = s.getInputStream(); ObjectInputStream ois = new ObjectInputStream(is); Student stu = (Student)ois.readObject(); System.out.println(stu); ois.close(); s.close(); } catch (Exception e) { e.printStackTrace(); } } }
人服务器代码如下:
import java.net.*; import java.io.*; public class ObjectServer { public static void main(String[] args) { try { ServerSocket ss = new ServerSocket(8001); Socket s = ss.accept(); OutputStream os = s.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(os); Student stu = new Student(1, "Ronnie", 37, "snooker"); oos.writeObject(stu); oos.close(); s.close(); ss.close(); } catch (Exception e) { e.printStackTrace(); } } }
要传递的对象类如下:
import java.io.Serializable; public 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; } public String toString() { return id + ", " + name + ", " + age + ", " + department; } }
注意:要传递的对象类必须实现Serializable接口