Kaiser4you
Kaiser4you

Reputation: 83

Serializing and Sending a Protocol Buffers Message

I have written this protobuf message in c#

Problem

I am trying to send a protobuf message from a c# client to this java server...

Question:

I should serialize this message to a byte array, so that i can send it to the java server... Unfortunately the method ProtoBuf.Serializer.Serialize dont return a byte array back. So how can i serialize it as a byte array and send it to my Java Server? Any help appreciated thanks!

Upvotes: 2

Views: 12607

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062502

protobuf-net (aka ProtoBuf.Serializer.Serialize) writes to streams. If you have the socket available as a NetworkStream, you can just write directly to that. If you really want a byte[], then use MemoryStream:

byte[] data;
using(var ms = new MemoryStream()) {
     Serializer.Serialize(ms, obj);
     data = ms.ToArray();
}

Upvotes: 4

Guido Simone
Guido Simone

Reputation: 7952

First you had better double check the protocol of the Java server. As described here protobuf is not self-delimiting. This means if you have a TCP connection and are sending multiple protobuf messages, there must be some other underlying protocol to take care of framing - determining where one message ends and another begins.

Let's ignore that problem for now. The actual code to serialize the message depends on which C#/protobuf library you are using. If you are using Jon Skeet's protobuf-csharp-port you might serialize it this way:

AddressBook book = InitializeAddressBook();
byte[] bookBytes = book.ToByteArray();

bookBytes is the address book, serialized to a byte array. Then use whatever socket library you want (for example TcpClient) to send the data (bookBytes) to the Java server.

I'm not convinced this will work because I think there are details about the Java server that you are not telling us.

Upvotes: 1

Related Questions