Richard Searle

home

Akka IO using byte[]

02 Feb 2013

http://www.kotancode.com/2013/02/02/sending-and-receiving-google-protocol-buffers-via-akka-io-and-scala/ Used the code from http://cognitiveentity.wordpress.com/2012/03/10/akka-system-io-client/ and http://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)
}
}