您的位置:首页 > 移动开发 > Android开发

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

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

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

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

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

public class MsgInfo implements Serializable {

/**
*
*/
private static final long serialVersionUID = 1L;
private String msgContent = null;
private String type = null;

public String getType() {
return type;
}

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

public String getMsgContent() {
return msgContent;
}

public void setMsgContent(String msgContent) {
this.msgContent = msgContent;
}
}

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



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



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

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

} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

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

ServerSocket serverSocket = new ServerSocket(8000);

while(true)
{
Socket socket = serverSocket.accept();
ObjectInputStream ois = null;
try {
while(true)
{

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

MsgInfo msgInfo = (MsgInfo)ois.readObject();
if(msgInfo.getType().equals("chat"))
{

System.out.println("Client's message"+msgInfo.getMsgContent());
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
finally
{

try {
if(ois != null)
ois.close();
if(socket != null)
socket = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}

这样我们就完成了Socket传输对象,当然,MsgInfo里可以封装一些其他的属性,这个就看你自己的项目需要了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐