主服务器和从服务器之间有连接。 我希望在main中使用Serialize消息,在slave中将它反序列化为对象。 所以我试着去做,我得到了一个例外:
The input stream is not a valid binary format. The starting contents (in bytes) are: 03-00-01-3F-C3-F5-E4-41-00-C0-8D-C3-14-EE-4A-C3-00 ...
我在代码中标记了DeSerialize中的内容。
我希望我的消息看起来像这样:ID消息(如1 \ 2 \ 3)+ OBJ:
-----------------------------
| ID | OBJECT |
-----------------------------
我的代码:
public override byte[] Serialize()
{
byte[] byteToSend = new byte[1024];
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
formatter.Serialize(stream, this);
byteToSend[0] = 3;
Array.Copy(stream.ToArray(), 0, byteToSend, 3, stream.ToArray().Length);
return byteToSend;
}
internal sealed class VersionConfigToNamespaceAssemblyObjectBinder : SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
Type typeToDeserialize = null;
try
{
string ToAssemblyName = assemblyName.Split(',')[0];
Assembly[] Assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly ass in Assemblies)
{
if (ass.FullName.Split(',')[0] == ToAssemblyName)
{
typeToDeserialize = ass.GetType(typeName);
break;
}
}
}
catch (System.Exception exception)
{
throw exception;
}
return typeToDeserialize;
}
}
public override BaseMassage DeSerialize(byte[] data)
{
MemoryStream stream = new MemoryStream(data);
BinaryFormatter formatter = new BinaryFormatter();
formatter.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
formatter.Binder = new VersionConfigToNamespaceAssemblyObjectBinder();
RadarMassage obj = (RadarMassage)formatter.Deserialize(stream); // ---- Here it falls
return obj;
}
经过大量搜索,我找到了这个例子。谢谢你的建议。 :)
答案 0 :(得分:0)
试试此代码
public override BaseMassage DeSerialize(byte[] data)
{
MemoryStream stream = new MemoryStream(data, 3, data.Length - 3);
BinaryFormatter formatter = new BinaryFormatter();
formatter.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
formatter.Binder = new VersionConfigToNamespaceAssemblyObjectBinder();
RadarMassage obj = (RadarMassage)formatter.Deserialize(stream);
return obj;
}