Android使用Serializable实现序列化传输对象

最近在做一个基于Socket通信项目,在实现客户端与服务器进行对象传输时使用到了Serializable接口对传输对象进行序列化,下面将和大家分享一下我的开发实例,欢迎各位交流探讨,不足之处希望各位多多指出。


首先谈谈什么是序列化,序列化(Serialization)是将对象的状态信息转换成可存储可传输的形式的这个过程,若要实现对象的传输,应该先将对象进行序列化。


在Android开发中可以使用Serializable及Parcelable对对象进行序列化,而Parcelable是Android特有的接口。我在进行Android客户端与Java服务器端进行通信的时候发现JavaSE没有支持Parcelable,所以这里只谈Serializable接口序列化。


用Serializable进行序列化非常简单,只需申明类实现Serializable接口,并实现get和set方法取得和设置属性即可。如:

  1. public class MsgInfo implements Serializable {

  2. /**
  3. *
  4. */
  5. private static final long serialVersionUID = 1L;
  6. private String msgContent = null;
  7. private String type = null;

  8. public String getType() {
  9. return type;
  10. }

  11. public void setType(String type) {
  12. this.type = type;
  13. }

  14. public String getMsgContent() {
  15. return msgContent;
  16. }

  17. public void setMsgContent(String msgContent) {
  18. this.msgContent = msgContent;
  19. }
  20. }

以上是我Android客户端的代码,若要实现客户端与服务器进行通信,服务器端MsgInfo的包名要与客户端一致,不然运行就会出现ClassNotFound的错误。


上面是Android客户端的MsgInfo类及它所在的包,同样,服务器端也应是一样的类名和包名。


下面是客户端实现对象传输的代码片段。

  1. try {
  2. Socket socket = new Socket("192.168.1.132", 8000);
  3. MsgInfo msgInfo = new MsgInfo();
  4. msgInfo.setType("chat");
  5. msgInfo.setMsgContent("hello!");
  6. ObjectOutputStream oos = null; //此处一定为ObjectOutputStream,因为传输的是MsgInfo对象 
  7. oos = new ObjectOutputStream(socket.getOutputStream()); 
  8. oos.writeObject(msgInfo);

  9. } catch (UnknownHostException e) {
  10. e.printStackTrace();
  11. } catch (IOException e) {
  12. e.printStackTrace();
  13. }

服务器端接收对象,代码片段:

  1. ServerSocket serverSocket = new ServerSocket(8000);

  2. while(true)
  3. {
  4. Socket socket = serverSocket.accept();
  5. ObjectInputStream ois = null;
  6. try {
  7. while(true)
  8. {

  9. ois = new ObjectInputStream(socket.getInputStream());

  10. MsgInfo msgInfo = (MsgInfo)ois.readObject();
  11. if(msgInfo.getType().equals("chat"))
  12. {
  13. System.out.println("Client's message"+msgInfo.getMsgContent());
  14. }
  15. }
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. } catch (ClassNotFoundException e) {
  19. e.printStackTrace();
  20. }
  21. finally
  22. {

  23. try {
  24. if(ois != null)
  25. ois.close();
  26. if(socket != null)
  27. socket = null;
  28. } catch (IOException e) {
  29. e.printStackTrace();
  30. }
  31. }
  32. }

这样我们就完成了Socket传输对象,当然,MsgInfo里可以封装一些其他的属性,这个就看你自己的项目需要了。吐舌头






  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值