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.
如何修改
同学你好,可以参考一下:
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