Richard Searle's Blog

Thoughts about software

Akka IO using byte[]

Posted by eggsearle on February 2, 2013

http://www.kotancode.com/2013/02/02/sending-and-receiving-google-protocol-buffers-via-akka-io-and-scala/

Used the code from https://cognitiveentity.wordpress.com/2012/03/10/akka-system-io-client/ and https://cognitiveentity.wordpress.com/2012/02/23/simpler-akka-io-example/ to send data serialized using ProtoBufs

These examples are all string based, primarily to make the code easy to test with curl.

The string representation of the length can be replaced with its 4 byte binary representation.
The payload is still a byte[], derived from a String for convenience

Client



case s: String => handle.foreach {
h =>
val bb = ByteBuffer.allocate(4)
bb.putInt(s.length)
bb.flip
h write ByteString(bb)
h write ByteString(s.getBytes("US-ASCII"))
 }

Server

 



def readMessage: IO.Iteratee[String] =
for {
lengthBytes <- take(4)
len = lengthBytes.asByteBuffer.getInt()
bytes <- take(len)
} yield {
ascii(bytes)
}
}

 

 

Advertisements

6 Responses to “Akka IO using byte[]”

  1. Thanks for the help on this code. The issue I had was I’m not sending a string, as the sample shows. I’m sending a protobuf object, which I am converting into a byte array, so instead of putInt(s.length) I’m using putInt(zombieMessage.getSerializedSize) and instead of s.getBytes(“US-ASCII”) I already have an array (messageBytes) , and I need to write that to the socket. I was using new String(messageBytes) before to deal with this, so I don’t know how to deal with it using your new sample…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: