序列化和发送协议缓冲区消息 [英] Serializing and Sending a Protocol Buffers Message
问题描述
我已经用c#编写了此protobuf消息
I have written this protobuf message in c#
-
C#客户端:
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;
}
问题
我正在尝试从c#客户端向该Java服务器发送protobuf消息...
I am trying to send a protobuf message from a c# client to this java server...
-
Java服务器
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(); }
}
}
问题:
我应该将此消息序列化为字节数组,以便可以将其发送到Java服务器... 不幸的是,方法 ProtoBuf.Serializer.Serialize 不会返回字节数组. 那么如何将其序列化为字节数组并将其发送到Java Server?任何帮助表示感谢!
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!
推荐答案
protobuf-net(又名ProtoBuf.Serializer.Serialize
)写入流.如果您将套接字用作NetworkStream
,则可以直接对其进行写入.如果您确实需要byte[]
,请使用MemoryStream
:
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();
}
这篇关于序列化和发送协议缓冲区消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!