所以我尝试使用以下代码通过网络流发送“数据包”类:
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);
}
}
}
答案 0 :(得分:2)
您不能从一个程序集中二进制序列化对象,并针对来自不同程序集的类反序列化它。
您需要从客户端和服务器引用第三个程序集。
答案 1 :(得分:1)
从BinaryFormatter反序列化时,该类必须可用。这就是错误所说的。
我假设在Client.dll中定义了Packet类。如果是这样,那么只需在“Server”项目中引用Client.dll并删除服务器中的Packet定义。
通常的做法是拥有一个可以与客户端和服务器共享的DataModel程序集。
此外,如果您使用XmlSerializer
而不是BinaryFormatter,那么您可以在客户端和服务器上使用不同的类实现。
答案 2 :(得分:0)
您创建了两个独立的(尽管功能相同)Packet类,并且您的客户端无法反序列化与序列化类型不同的类型,即使它们具有相同的名称和结构。
尝试在类库类型的单独第三个项目/程序集中定义Packet类。然后,从客户端和服务器引用该项目或程序集。更准确的说,您可以在此类库中定义一个接口IPacket,并在客户端和服务器中实现它。
希望有所帮助。