解码消息时出现反序列化异常

时间:2015-07-10 04:38:35

标签: c# sockets exception networking serialization

我正在开发一个利用简单Socket连接的项目,使用Packet.cs对象作为“旅行模式”在客户端和服务器之间传递小变量。客户端和服务器是不同项目的一部分,但是相同的解决方案,Packet.cs也是一个单独的“共享项目”。

这是我的packet.cs文件:

using System;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace ConnectionData
{
    [Serializable]
    public class Packet
    {
        // these are all the different types of things we can send
        public List<string> gData;
        public string packetString;
        public int packetInt;
        public bool packetBool;
        public PacketType packetType;

        // senderID is going to be the unique GUID that we generated
        public string senderID;


        public Packet (PacketType type, string senderID)
        {
            gData = new List<String> ();
            this.senderID = senderID;
            this.packetType = type;
        }

        public Packet(byte[] packetBytes)
        {
            // deconstructs the bytes we received into packet form
            BinaryFormatter bf = new BinaryFormatter ();
            MemoryStream ms = new MemoryStream (packetBytes);

            Packet p = (Packet)bf.Deserialize (ms);
            ms.Close ();

            // assigns all the values from the packet info we received in byte form
            this.gData = p.gData;
            this.packetInt = p.packetInt;
            this.packetBool = p.packetBool;
            this.senderID = p.senderID;
            this.packetType = p.packetType;
        }

        // this converts the whole packet object into a byte array to send through the socket
        public byte[] ToBytes()
        {
            BinaryFormatter bf = new BinaryFormatter ();
            MemoryStream ms = new MemoryStream ();

            bf.Serialize (ms, this);
            byte[] bytes = ms.ToArray ();
            ms.Close ();
            return bytes;
        }

        // this function will return the active IP address of the system. if it
        // cant find one, it returns default local address
        public static string GetIP4Address()
        {
            // this lists all addresses shown in IPConfig
            IPAddress[] ips = Dns.GetHostAddresses (Dns.GetHostName ());

            foreach(IPAddress i in ips)
            {
                // if there's an IP4 address in the list, return it
                if (i.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) 
                {
                    return i.ToString ();
                }       
            }

            // else return local address
            return "127.0.0.1"; 
        }

        // enum makes it so we can define different strings, makes the packetType really easy to work with
        // allows us to define what kind of packet it is
        public enum PacketType
        {
            Registration, CloseConnection, Command
        }
    }
}

这是我用来发送数据的。当我在服务器上创建要发送给客户的消息时,我只需致电Packet p = new Packet(Packet.PacketType.Command);socket.Send(p.ToBytes());

接收数据包(在两个项目上)使用:

public void Data_IN (object cSocket)
        {
            Socket clientSocket = (Socket)cSocket;

            byte[] buffer;
            int readBytes;

            while (Server.listening) {
                // sets our buffer array to the max size we're able to receive
                buffer = new byte[clientSocket.SendBufferSize];

                // gets the amount of bytes we've received
                readBytes = clientSocket.Receive (buffer);

                // if we actually recieve something, then sort through it
                if (readBytes > 0) {
                    // handle data
                    Packet packet = new Packet (buffer);
                    DataManager (packet); // handles the packet data
                }
            }
        }

当我尝试在第一次连接时发送注册数据包时出现问题。我启动我的服务器项目并让它执行只是等待,一切正常。客户端能够连接,服务器发送在此创建的注册数据包:

Packet p = new Packet (Packet.PacketType.Registration, Server.guid);
p.packetString = HeartCore.commandKey; // commandKey is a static string variable
clientSocket.Send (p.ToBytes ());

服务器显示已成功发送,然后客户端抛出异常。好极了!客户端使用Data_IN处理收到的数据包,如上所示。在

中创建新数据包后立即发生异常
if (readBytes > 0) {
    // handle data
    Packet packet = new Packet (buffer); // this is where it stops
    DataManager (packet); // handles the packet data
}

public Packet(byte[] packetBytes)
{
    // deconstructs the bytes we received into packet form
    BinaryFormatter bf = new BinaryFormatter ();
    MemoryStream ms = new MemoryStream (packetBytes);

    Packet p = (Packet)bf.Deserialize (ms); //EXCEPTION OCCURS HERE
    ms.Close ();
    ...

如果你还记得,数据包类有一个构造函数,它接受byte []缓冲区并将其转换为一个对象,然后将临时数据包对象的值复制到正在使用的实际对象。

抛出的异常是

System.Runtime.Serialization.SerializationException: Couldn't find assembly 'Heart' ---> System.Exception: Could not load file or assembly 'Heart' or one of its dependencies. The system cannot find the file specified.
  at System.AppDomain.Load (System.String assemblyString, System.Security.Policy.Evidence assemblySecurity, Boolean refonly) [0x00000] in <filename unknown>:0
  at System.AppDomain.Load (System.String assemblyString) [0x00000] in <filename unknown>:0
  at at (wrapper remoting-invoke-with-check) System.AppDomain:Load (string)
  at System.Reflection.Assembly.Load (System.String assemblyString) [0x00000] in <filename unknown>:0
  at System.Runtime.Serialization.Formatters.Binary.ObjectReader.GetDeserializationType (Int64 assemblyId, System.String className, Boolean throwOnError) [0x00000] in <filename unknown>:0
  --- End of inner exception stack trace ---
  at System.Runtime.Serialization.Formatters.Binary.ObjectReader.GetDeserializationType (Int64 assemblyId, System.String className, Boolean throwOnError) [0x00000] in <filename unknown>:0
  at System.Runtime.Serialization.Formatters.Binary.ObjectReader.GetDeserializationType (Int64 assemblyId, System.String className) [0x00000] in <filename unknown>:0
  at System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadTypeMetadata (System.IO.BinaryReader reader, Boolean isRuntimeObject, Boolean hasTypeInfo) [0x00000] in <filename unknown>:0
  at System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadObjectInstance (System.IO.BinaryReader reader, Boolean isRuntimeObject, Boolean hasTypeInfo, System.Int64& objectId, System.Object& value, System.Runtime.Serialization.SerializationInfo& info) [0x00000] in <filename unknown>:0
  at System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadObject (BinaryElement element, System.IO.BinaryReader reader, System.Int64& objectId, System.Object& value, System.Runtime.Serialization.SerializationInfo& info) [0x00000] in <filename unknown>:0
  at System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadObject (BinaryElement element, System.IO.BinaryReader reader, System.Int64& objectId, System.Object& value, System.Runtime.Serialization.SerializationInfo& info) [0x00000] in <filename unknown>:0
  at System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadNextObject (BinaryElement element, System.IO.BinaryReader reader) [0x00000] in <filename unknown>:0
  at System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadObjectGraph (BinaryElement elem, System.IO.BinaryReader reader, Boolean readHeaders, System.Object& result, System.Runtime.Remoting.Messaging.Header[]& headers) [0x00000] in <filename unknown>:0
  at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.NoCheckDeserialize (System.IO.Stream serializationStream, System.Runtime.Remoting.Messaging.HeaderHandler handler) [0x00000] in <filename unknown>:0
  at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize (System.IO.Stream serializationStream) [0x00000] in <filename unknown>:0
  at ConnectionData.Packet..ctor (System.Byte[] packetBytes) [0x00016] in /home/austin/Programming/C#/Crystal-Home-Systems/ConnectionData/Packet.cs:63
  at Shard.Client.Data_IN () [0x0002f] in /home/austin/Programming/C#/Crystal-Home-Systems/Shard/Client.cs:90
  at System.Threading.Thread.StartInternal () [0x00000] in <filename unknown>:0

现在,我对C#本身不熟悉,但我对Java有着相当丰富的经验,之前已经完成了这种类型的服务器客户端工作。我花了大约5个小时改变了一切,使用谷歌,甚至询问了几个编程朋友,我们一直无法弄清楚发生了什么。 Couldn't find assembly 'Heart'指的是我想到项目Heart,它是发送导致崩溃的数据包的服务器类。

有谁知道可能导致崩溃的原因是什么?我很生气,觉得我错过了一些非常明显的东西。我试着尽可能具体,如果我忘记提问或者你需要更多细节,请告诉我!

非常感谢你提前帮忙!

编辑:只是为了澄清,服务器和客户端能够毫无问题地连接,尝试解码服务器发送给客户端的注册数据包时会发生错误。此外,它使用单声道在Linux系统Kubuntu上运行。我不认为这会有所作为,但它可能

2 个答案:

答案 0 :(得分:1)

通过使用bf.Serialize (ms, this)发送数据包,您的客户端需要包含typeof(this)的程序集,即Heart程序集。然后客户端需要该程序集对其进行反序列化。

不要序列化内部结构(Packet),序列化您移动到程序集中的Payload类,并与客户端共享。

但问题是这段代码:

// gets the amount of bytes we've received
readBytes = clientSocket.Receive (buffer);

// if we actually recieve something, then sort through it
if (readBytes > 0) {
    // handle data
    Packet packet = new Packet (buffer);
    DataManager (packet); // handles the packet data
}

可以在少量呼叫中使用localhost,但在达到任何严重流量时都会失败,因为buffer可以包含半条消息或三条半消息。

您需要实施成帧协议来检测单独的消息。

但是当你这样做时,你似乎正在从头开始重新创建Protocol Buffers。使用existing libraries这样的内容。

答案 1 :(得分:0)

我找到了问题的答案。 Packet.cs文件位于共享项目中。据我所知,共享项目使用解决方案中所有其他项目的资源,这不是我想要做的。

我尝试了各种各样的事情,包括CodeCaster给出的惊人答案,但没有任何效果。

要解决异常,我将Packet.cs文件重新编译为共享库项目,而不是共享项目。这允许将Packet.cs文件作为.dll文件放入构建路径,使其不具有其他项目的资源。

完美构建并执行解决方案!我希望这有助于将来的某个人!