使用TCPClient的NetworkStream和protobuf-net,我通过TCP发送和接收protobuf消息 .
看到一个类似的问题:How to properly handle incoming protobuf message with a NetworkStream?
但在我的情况下,只能有一种消息类型,所以我不认为我需要一个解析器 .
所以我序列化我的对象并使用tcp / ip发送它,在我的服务器上我尝试反序列化它并获得io异常:无法从传输连接中读取数据 .
客户:
...
using (var ms = new MemoryStream())
{
Serializer.Serialize(ms, person);
data = ms.ToArray();
}
NetworkStream stream = client.GetStream();
stream.Write(data, 0, data.Length);
服务器:
...
Byte[] bytes = new Byte[256];
String data = null;
while(true)
{
Console.Write("Waiting for a connection... ");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
NetworkStream stream = client.GetStream();
Person newPerson = Serializer.Deserialize<Person>(stream);<--- exeption
}
1 回答
我认为这里的简短版本是:使用
SerializeWithLengthPrefix
和DeserializeWithLengthPrefix
. 默认的protobuf行为是"read to the end of the stream" . 在序列化时你不应该需要MemoryStream
,btw;你应该Serialize
直接到NetworkStream
. 如果由于其他原因需要MemoryStream
,您可以使用以下方法保存自己的数据副本: