user3770158
user3770158

Reputation: 389

How to handle incoming protobuf message

Using TCPClient's NetworkStream and protobuf-net I send and receive protobuf messages via TCP.

Saw a similar question: How to properly handle incoming protobuf message with a NetworkStream?

But in my case there can only be one message type so i dont think i need a resolver.

So i serialized my object and send it using tcp/ip, on my server i try to deserialize it and get io exception: Unable to read data from the transport connection.

Client:

...
using (var ms = new MemoryStream())
{
    Serializer.Serialize(ms, person);

    data = ms.ToArray();
}
NetworkStream stream = client.GetStream();

stream.Write(data, 0, data.Length);

Server:

...
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
 }

Upvotes: 2

Views: 940

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064184

I think the short version here is: use SerializeWithLengthPrefix and DeserializeWithLengthPrefix. The default protobuf behaviour is "read to the end of the stream". You shouldn't need the MemoryStream when serializing, btw; you should be fine to Serialize directly to the NetworkStream. If you need the MemoryStream for other reasons, you can save yourself a copy of the data by using:

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

Upvotes: 1

Related Questions