首页 > 代码库 > SOCKET实现对象传输【java实现】
SOCKET实现对象传输【java实现】
/*客户端*/ 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"; } }
本文出自 “black4yL” 博客,请务必保留此出处http://black4yl.blog.51cto.com/4222963/1589686
SOCKET实现对象传输【java实现】
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。