要传递的简单数据协定类:
[DataContract]
public class MyData
{
[DataMember]
public float Value1 {get;set;}
[DataMember]
public float Value2 {get;set;}
[DataMember]
public float Value3 {get;set;}
}
服务器代码:
var serializer = new DataContractSerializer(typeof(MyData));
using (var pipe = new NamedPipeServerStream("testpipe", PipeDirection.InOut))
{
pipe.WaitForConnection();
var data = new MyData
{
Value1 = 200,
Value2 = 456,
Value3 = 10234.33f
};
serializer.WriteObject(pipe, data);
}
客户端代码:
var serializer = new DataContractSerializer(typeof(MyData));
using (var client = new NamedPipeClientStream(".", "testpipe", PipeDirection.InOut))
{
client.Connect();
var data = (MyData)serializer.ReadObject(client);
}
对上面的调用ReadObject
只是挂起而不抛出任何异常。使用 XmlSerializer 是完全相同的。
这些序列化程序甚至可以直接在命名管道流上使用,还是被迫使用手动字符串/字节消息解析?