Android编程实战——仿微信群聊-2——对象的网络传输

Android编程实战——仿微信群聊-2——对象的网络传输

项目源代码移步github

上一章服务器端有个消息类MyMessage类没有细讲,这里就说一下MyMessage和更重要的网络中对象的传输(对象的序列化和反序列化)。
首先要先了解到数据在网络中的传输是通过输入输出流来进行的。
为了传输的方便性,我们将数据打包封装起来,一般一个最简单的消息体需要有目的,来源,消息内容这三个属性。具体的也可以自己扩展。

MyMessage类:

public class MyMessage implements Serializable{

    private static final long serialVersionUID = 1L;

    public static final int MSG_AUDIO = 1; //消息类型,语音消息
    public static final int MSG_LOGIN = 2; //消息类型,登录消息
    public static final int MSG_TEXT = 3; //消息类型,文本消息
    public static final int MSG_AUDIO_MARK= 4;// 消息类型,语音消息的标识

    private String tip = ""; //额外附带的消息,这里也可以把所有消息放在一起然后通过分隔符区分
    private int msgType = -1; //消息类型
    private String sendName = ""; //发送者
    private String msgContent = ""; //消息内容String
    private byte[] msgContentBinary; //消息内容,用来传输文件


    // Getter Setter
    public String getTip() {
        return tip;
    }
    public void setTip(String tip) {
        this.tip = tip;
    }

    public void setMsgType(int msgType) {
        this.msgType = msgType;
    }

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

    public byte[] getMsgContentBinary() {
        return msgContentBinary;
    }

    public void setMsgContentBinary(byte[] msgContentBinary) {
        this.msgContentBinary = msgContentBinary;
    }

    public void setSendName(String sendName) {
        this.sendName = sendName;
    }

    public int getMsgType() {
        return msgType;
    }

    public String getSendName() {
        return sendName;
    }

    public String getMsgContent() {
        return msgContent;
    }


    /**
     * 构造方法
     * @param msgType 消息类型
     * @param msgContent 消息内容String
     */
    public MyMessage(int msgType, String msgContent) {
        this.msgType = msgType;
        this.msgContent = msgContent;
    }

    public MyMessage() {

    }

    /**
     * 构造方法
     * @param msgType 消息类型
     * @param msgContentBinary 消息内容,文件数据
     */
    public MyMessage(int msgType, byte[] msgContentBinary) {
        this.msgType = msgType;
        this.msgContentBinary = msgContentBinary;
    }
}

这里因为我只做了群聊,没有做私聊所以没有目的人这个属性,后来我发现好像用键值对Put 和 Get方法可能更方便,大家可以自己扩展实现。

要用流来传输对象,就必须要对对象进行序列化和反序列化了,在Java中这些操作还是很方便的,让需要序列化的类实现Serializable接口,然后用ObjectInputStream和ObjectOutputStream的readObject()和WriteObject()方法就可以了。实现了这个接口后可以定义这个属性serialVersionUID,用来保证服务端和客户端这两个类是相同的,这个属性可以由编译器生成或者自己指定。
对象的网络传输有一点需要注意:两个类的目录必须是相同的,不然会报ClassNoFound异常。

对象的序列化方法是Java默认自带的,我们也可以自己实现序列化这个过程。通过类实现readObject(ObjectInputStream in)和writeObject(ObjectOutputSteam out)方法,在方法里面自定义序列化方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值