0

因此,我尝试使用以下代码通过网络流发送“数据包”类:

IFormatter formatter = new BinaryFormatter();
NetworkStream stream = client.GetStream();
formatter.Serialize(stream, packet);


stream.Flush();
stream.Close();
client.Close();

使用这个类:

[Serializable]
public class Packet
{

    public string header;
    public string content;
    public int size = 0;

    public Packet(string header, string content)
    {
        this.header = header;
        this.content = content;

        size = Encoding.ASCII.GetByteCount(header) + Encoding.ASCII.GetByteCount(content);
    }
}

但是在另一边阅读时出现以下错误:

'System.Runtime.Serialization.SerializationException: Unable to find assembly 'Client, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.'

这是我的阅读代码:

NetworkStream ns = client.GetStream();
IFormatter formatter = new BinaryFormatter();
Packet p = (Packet)formatter.Deserialize(ns);
MessageBox.Show(p.header);
return p;

知道为什么会这样吗?

编辑:

服务器端数据包类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Server
{

    public class Packet
    {
        public string header;
        public string content;
        public int size = 0;

        public Packet(string header, string content)
        {
            this.header = header;
            this.content = content;

            size = Encoding.ASCII.GetByteCount(header) + Encoding.ASCII.GetByteCount(content);
        }
    }
}
4

3 回答 3

2

您不能对来自一个程序集的对象进行二进制序列化,并针对来自不同程序集的类对其进行反序列化。

您需要从客户端和服务器都引用第三个程序集。

于 2013-02-06T05:51:53.180 回答
1

当您从 BinaryFormatter 反序列化时,该类必须可用。这就是错误所说的。

我假设 Packet 类是在 Client.dll 中定义的。如果是这样,那么只需在“服务器”项目中引用 Client.dll 并删除服务器中的数据包定义。

一般的做法是拥有一个可以与 Client 和 Server 共享的 DataModel 程序集。

此外,如果您使用XmlSerializer而不是 BinaryFormatter,那么您可以在客户端和服务器上拥有该类的不同实现。

于 2013-02-06T05:50:13.093 回答
0

您创建了两个单独的(尽管功能相同)Packet 类,并且您的客户端无法反序列化与已序列化的类型不同的类型,即使它们具有相同的名称和结构。

尝试在类库类型的单独的第三个项目/程序集中定义 Packet 类。之后,从您的客户端和服务器中引用该项目或程序集。更正确的是,您将在此类库中定义一个 Interface IPacket 并在您的客户端和服务器中简单地实现它。

希望有帮助。

于 2013-02-06T05:56:15.583 回答