问题
I have written this protobuf message in c#
C# client:
public AddressBook InitializeAdressBook() { Person newContact = new Person(); AddressBook addressBookBuilder = new AddressBook(); Person john = new Person(); john.id=1234; john.name="John Doe"; john.email="jdoe@example.com"; Person.PhoneNumber nr = new Person.PhoneNumber(); nr.number="5554321"; john.phone.Add(nr); addressBookBuilder.person.Add(john); TextBox.Text += ("Client: Initialisiert? " + addressBookBuilder.ToString()) + "\t" + "\n"; TextBox.Text += " Erster Person " + addressBookBuilder.person.First().name + "\t" + "\n"; return addressBookBuilder; }
Problem
I am trying to send a protobuf message from a c# client to this java server...
Java server
public ControllerThread(Socket s){ this.s = s; try { AddressBook adb = AddressBook.parseFrom(s.getInputStream()); System.out.println("Server: Addressbook:" + adb.getPersonCount()); } catch (IOException e) { System.out.println("Server: BufferedReader oder PrintWriter von ThermoClient konnte nicht erstellt werden"); e.printStackTrace(); } }
}
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!
回答1:
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();
}
回答2:
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.
来源:https://stackoverflow.com/questions/13165690/serializing-and-sending-a-protocol-buffers-message