/*客户端*/ import person.*; import java.net.InetAddress; import java.net.Socket; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; public class client { public static void main(String[] args) { try { Socket soc = new Socket(InetAddress.getLocalHost(),8020); OutputStream o = soc.getOutputStream(); ObjectOutput s = new ObjectOutputStream(o); Person person = new Person("Tony",25,"Female","han"); s.writeObject(person); s.flush(); s.close(); }catch(Exception e) { System.out.println(e.getMessage()); System.out.println("Error during Serialization"); System.exit(1); } } }
/*服务端*/ import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.net.ServerSocket; import java.net.Socket; import person.Person; public class Server { public static void main(String[] args) { ServerSocket ser = null; Socket soc = null; //接受客户端连接 Person person = null; try{ ser = new ServerSocket(8020); soc = ser.accept(); InputStream o = soc.getInputStream(); ObjectInput s = new ObjectInputStream(o); person = (Person)s.readObject(); s.close(); System.out.println(person); }catch(Exception e) { System.out.println(e.getMessage()); System.out.println("Errior during serialization"); System.exit(1); } } }
/*要传输的对象*/ import java.io.Serializable; public class Person implements Serializable{ public String name; public int age; public String sex; public String nationlity; public Person(String name,int age,String sex,String nationlity) { this.name = name; this.age = age; this.sex = sex; this.nationlity = nationlity; } public String toString() { return "Name:" + name + "\nAge:"+ age + "\nSex:" + sex + "\nnationality:" + nationlity + "\n\n"; } }
时间: 2024-10-01 03:19:36