JAVA 通过网络传输对象(对象序列化)简单示例

来源:互联网 发布:七天精通js 编辑:程序博客网 时间:2024/06/06 09:43

首先,要传输的Student类(实现Serializable接口):

public class Student implements Serializable{private static final long serialVersionUID = 8683452581334592189L;private String name;private int age;private int score;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public int getScore() {return score;}public void setScore(int score) {this.score = score;}@Overridepublic String toString() {// TODO Auto-generated method stubreturn "name:" + name + " age:" + age + " score:" + score;}}

Socket服务器类核心方法:


public static void openObjectServer(){ServerSocket ss = null;try {ss = new ServerSocket(1111);while(true){final Socket socket = ss.accept();new Runnable(){public void run() {try {InputStream is = socket.getInputStream();OutputStream os = socket.getOutputStream();os.write("欢迎连接 服务器 一号!".getBytes());ObjectInputStream ois = new ObjectInputStream(is);Object object = ois.readObject();//打印对象System.out.println(object);//关闭socketsocket.close();}catch(Exception e){e.printStackTrace();}finally{if(socket != null )try {socket.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}.run();}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{System.out.println("服务器关闭连接!");try {if(ss != null)ss.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}


说明:该服务器方法可以接受多个客户端连接,一般网络服务器编程核心思想应该都是这样,开启后,支持多线程处理多个连接请求,互不影响。


Socket客户端类:


public class ClientSocketClass {public static void main(String[] args){Socket socket = null;try{socket = new Socket(InetAddress.getByName("127.0.0.1"),1111);OutputStream os = socket.getOutputStream();ObjectOutputStream oos = new ObjectOutputStream(os);Student student = new Student();student.setAge(20);student.setName("wjw");student.setScore(100);oos.writeObject(student);}catch(Exception e){e.printStackTrace();}finally{try {if(socket != null)socket.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}


说明:将对象序列化,通过网络传输给服务器。


结果:在服务器端可以成功接收对象并打印。


如有错误,欢迎指正

end



原创粉丝点击