BinaryFormatter反序列化有时会抛出异常

时间:2013-06-29 20:31:00

标签: c# serialization

我有客户端和服务器端应用程序的项目。当然,他们交换数据。我正在测试大型对象(大约5 mb)上的数据流并遇到问题: 有时BinaryFormatter Deserialize()抛出此异常:

二进制流“0”不包含有效的BinaryHeader。可能的原因是序列化和反序列化之间无效的流或对象版本更改。 ---(不一定是流'0',但也可能是其他索引)。我检查了数据的大小(在发送方和接收方都是)并且它们是相同的,但内容(平均字节顺序与发送的数据包不同)。 代码如下:

 public static ICommand Deserialize(byte[] bytes)
    {


        BinaryFormatter frmt=new BinaryFormatter();
        frmt.AssemblyFormat = FormatterAssemblyStyle.Simple;
        frmt.Binder=new BindingType();
        using (MemoryStream ms = new MemoryStream(bytes))
        {
            ms.Seek(0, SeekOrigin.Begin);
            return (ICommand)frmt.Deserialize(ms);
        }
    }

    private class BindingType:SerializationBinder//for deserializeing object in     assembly, different from where serialized
    {
        public override Type BindToType(string assemblyName, string typeName)
        {
            Type toDeserialize = null;
            String exeAssembly = Assembly.GetExecutingAssembly().FullName;
            if (typeName == "Server.ServerPlayer")
                typeName = "Command_Entities.Player";
            if (typeName == "Server.ServerLobby")
                typeName = "Command_Entities.Lobby";


            // The following line of code returns the type.
            toDeserialize = Type.GetType(String.Format("{0}, {1}",typeName, exeAssembly));//change assembly name and type accordingly to object being deserialized
            //to match current assembly name

            return toDeserialize;
        }
    }

这是我的接收逻辑:

 private void AsyncReceiveLoop(object obj)
    {
        byte[] metaData = new byte[4];
        byte[] data = null;
        int received = 0;
        try
        {
            while (!_stop)
            {
                _me.Receive(metaData, 0, 4, SocketFlags.None);
                _packetSize =Convert.ToInt32( BitConverter.ToUInt32(metaData, 0));
                data = CorrectReceiver.Receive(_me, _packetSize).ToArray();


                if (_packetSize == data.Length)
                {
                    _mainCallback(data);
                }

            }

        }
        catch (SocketException ex)
        {
            _ecxeptionCallback(ex);
        }

    }

这一个(CorrectReceiver):

  public static byte[] Receive(Socket soc, int packetSize)
    {

        NetworkStream ns=new NetworkStream(soc,false);
        List<byte> totalBytes=new List<byte>();
        int receivedTotal = 0;
        byte[] tempBytes=null;
        int size = 0;
        int received = 0;
        int available = 0;
        byte[] rec = null;
        tempBytes = new byte[packetSize];
        while (packetSize > receivedTotal)
        {

            if (ns.DataAvailable)
            {



                received=ns.Read(tempBytes, receivedTotal, packetSize-receivedTotal);
                if(received==0)
                    throw new Exception("Connection closed...");//connection closed when 0 bytes received

                receivedTotal += received;


            }
            else{ System.Threading.Thread.Sleep(50);}

        }
        return tempBytes;
    }

你可能会在这里找到一些不必要或愚蠢的解决方案,但这个问题持续很长时间,我在代码和逻辑方面做了很多改变。 所以,如果你们中的任何人在这里看到某些东西,这可能是问题的原因,或者如果过去有人遇到过这个问题,请帮助我找到错误。

1 个答案:

答案 0 :(得分:1)

我解决了这个问题,问题在于线程化:我在AsyncReceiveLoop中切换线程并得到了这个奇怪的bug。在某些时候,交换机旧线程正在读取字节并且在新线程读取截断字节之后。应始终小心交叉线程。谢谢。