Protocol Buffer Messages via Akka IO and Sockets

坚强是说给别人听的谎言 提交于 2019-12-22 07:07:10

问题


I came across this blog post, which I found awesome and enlightening, showing how to do fixed-length framing of string messages sent to an Akka IO socket server. I have been working with an open source library I found here called ScalaBuff, which creates a nice thin layer on top of protocol buffer objects.

The trouble I'm having is in adapting the blog author's (couldn't find a link to contact him directly) code to take the length (4-byte sequence) and then the protobuf byte array. I can worry about figuring out which message is on the wire later, right now I just want to get the code to work with one sample message.

My issue is that I am having trouble converting the Akka IO code from pulling akka ByteStrings into being able to send and pull the raw bytes from the protobuf message. This is a symptom of my lack of familiarity with socket servers using Akka IO. I can get to and from the byte representation of my protobuf object (a Zombie Sighting), but I just can't get the sample from the blog to work on byte arrays instead of strings.

If anybody has some advice, some sample code, or some input on how to get from point A (the blog post mentioned above) to point B (an Akka IO socket client that sends a protobuf message to an Akka IO socket server.. I think I have the client working.. maybe), that would be awesome.


回答1:


Try this:

val myByteArray = myByteString.toArray // converts to an Array[Byte]
val myMessage = MyMessage.defaultInstance.mergeFrom(myByteArray)

MyMessage is the ScalaBuff-compiler-generated class using your MyMessage.proto template. Note that the Google protobuf library has a separate ByteString class, make sure you don't mix the two.

UPDATE: Kevin's problem has been solved, basically the problem was the he was using the toString method of an Array[Byte] instead of wrapping the byte array in a new String(), which correctly converts the byte array to a String, to be used in a "%s".format call.



来源:https://stackoverflow.com/questions/14657435/protocol-buffer-messages-via-akka-io-and-sockets

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