Unity - A计划(永久有效期) 扫二维码继续学习 二维码时效为半小时

(197评价)
价格: 4431.00元
序列化 和 反序列的问题
Lemonsuan发起了问答2022-03-16
2
回复
254
浏览
public void Test()
    {
        Msg msg = new Msg(CommandCode.Login, MethodCode.Login, ErrorCode.None);
        byte[] data= PackData(msg);

        Msg newmsg = ParseData(data, 0, data.Length);
        Debug.Log(newmsg.cmd);
    }
    public byte[] PackData(Msg msg)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            BinaryFormatter bin = new BinaryFormatter();
            bin.Serialize(ms, msg);
            byte[] con = ms.ToArray();
            
            byte[] len = BitConverter.GetBytes(con.Length);
            return len.Concat(con).ToArray();
        }
    }
    public Msg ParseData(byte[] content, int readIndex, int dataLengtth)
    {
        Msg msg = null;
        byte[] newByte = new byte[dataLengtth];
        Array.Copy(content, readIndex, newByte, 0, dataLengtth);

        using (MemoryStream ms = new MemoryStream(newByte, 0, newByte.Length))
        {
            BinaryFormatter bin = new BinaryFormatter();
            msg = bin.Deserialize(ms) as Msg;
        }

        return msg;
    }
using System;

[Serializable]
public class Msg
{
    public CommandCode cmd;
    public MethodCode method;
    public ErrorCode error;

    public Msg(CommandCode cmd, MethodCode method, ErrorCode error)
    {
        this.cmd = cmd;
        this.method = method;
        this.error = error;
    }
}


[Serializable]
public class LoginMsg : Msg
{
    public string user;
    public string pwd;
    public LoginMsg(CommandCode cmd, MethodCode method, ErrorCode error,string user,string pwd) : base(cmd, method, error)
    {
        this.user = user;
        this.pwd = pwd;
    }
}

出现了 SerializationException: Binary stream '0' does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization.

如何修改

所有回复
  • 老师_Trigger 2022-03-17

    同学你好,可以参考一下:

    https://www.it1352.com/1836221.html

    https://stackoverflow.com/questions/15134031/binary-stream-0-does-not-contain-a-valid-binaryheader

    https://stackoverflow.com/questions/3606507/frustrating-tcp-serialization-exception-binary-stream-0-does-not-contain-a-va

    还有-4条回复,点击查看
    你还没有登录,请先登录注册
发表回复
你还没有登录,请先 登录或 注册!