Serializing and Sending a Protocol Buffers Message

只谈情不闲聊 提交于 2019-12-06 11:41:29

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();
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!