我有一个传输应用程序,它用作pub- / sub服务器在客户端之间中继数据。 pub- / sub服务器只需要了解一些数据,例如它需要topicname能够将已发布的主题转发给正确的订阅者。
为了达到这个目的,我想到了一个方案,其中一个被装饰为ProtoContract的类包含一个byte [],而byte []又包含protobuf-net序列化数据。通过这种方式,服务器只需要对其中继的数据的一小部分进行反序列化(并且不需要知道类型)。我的类型看起来像这样;
[ProtoContract]
public class DataFrame
{
/// <summary>
/// Time the data was issued or sampled. In UTC time.
/// </summary>
[ProtoMember(1)]
public DateTime TimeStamp = DateTime.UtcNow;
/// <summary>
/// The topic associated with the data
/// </summary>
[ProtoMember(2)]
public string TopicName = string.Empty;
/// <summary>
/// Command, can be either Discover, Subscribe, Unsubscribe or Publish
/// </summary>
[ProtoMember(3)]
public string Command = string.Empty;
/// <summary>
/// The fully qualified type name of the content
/// </summary>
[ProtoMember(4)]
private string _typeName = string.Empty;
/// <summary>
/// Serialized content data (if any)
/// </summary>
[ProtoMember(5)]
private byte[] _content;
/// <summary>
/// The fully qualified type name of the content
/// </summary>
public string TypeName
{
get
{
return _typeName;
}
}
/// <summary>
/// Get the content of this DataFrame
/// </summary>
/// <typeparam name="T">Type of the content</typeparam>
/// <returns>The content</returns>
public T GetContent<T>()
{
MemoryStream ms = new MemoryStream(_content);
return Serializer.DeserializeWithLengthPrefix<T>(ms, PrefixStyle.Base128);
}
/// <summary>
/// Set the content for this DataFrame
/// </summary>
/// <param name="value">The content to set, must be serializable and decorated as a protobuf contract type</param>
public void SetContent<T>(T value)
{
MemoryStream ms = new MemoryStream();
Serializer.SerializeWithLengthPrefix(ms, value, PrefixStyle.Base128);
_content = ms.GetBuffer();
_typeName = value.GetType().AssemblyQualifiedName;
}
/// <summary>
/// Encode the frame to a serialized byte array suitable for tranmission over a network
/// </summary>
/// <returns>The encoded byte[]</returns>
public byte[] Encode()
{
DataFrame frame = (DataFrame)this;
MemoryStream ms = new MemoryStream();
Serializer.SerializeWithLengthPrefix(ms, frame, PrefixStyle.Base128);
return ms.GetBuffer();
}
/// <summary>
/// Factory function to create a frame from a byte array that has been received
/// </summary>
/// <param name="buffer">The serialized data to decode</param>
/// <returns>A new dataframe decoded from the byte[]</returns>
public static DataFrame Decode(byte[] buffer)
{
MemoryStream ms = new MemoryStream(buffer);
DataFrame frame = Serializer.DeserializeWithLengthPrefix<DataFrame>(ms, PrefixStyle.Base128);
frame._timeStamp = DateTime.SpecifyKind(frame._timeStamp, DateTimeKind.Utc);
return frame;
}
}
问题是,我能够反序列化DataFrame,但是当反序列化有效负载byte []时,我得到了protobuf异常。也就是说,这是有效的(服务器是UdpClient);
data = server.Receive(ref remoteEP);
DataFrame frame = DataFrame.Decode(data);
但即使内容是字符串,这也会给我一个protobuf异常;
string content = frame.GetContent<string>();
有没有人对我做错了什么有任何指示?