【问题标题】:How to handle incoming protobuf message如何处理传入的 protobuf 消息
【发布时间】:2015-01-06 16:14:47
【问题描述】:

使用 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
 }

【问题讨论】:

    标签: c# tcp protobuf-net


    【解决方案1】:

    我认为这里的简短版本是:使用SerializeWithLengthPrefix 和DeserializeWithLengthPrefix。默认的 protobuf 行为是“读到流的末尾”。顺便说一句,序列化时你不应该需要MemoryStream;你应该可以直接到SerializeNetworkStream。如果您出于其他原因需要MemoryStream,您可以使用以下方法为自己保存一份数据:

    stream.Write(ms.GetBuffer(), 0, (int)ms.Length);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      • 2020-12-28
      相关资源
      最近更新 更多