nbokmans nbokmans - 1 year ago 204
Scala Question

How to convert Akka ByteString into String?

I'm sorry if this is a dumb question but I can honestly not figure it out without setting up some kind of ASCII code -> character mapper myself, which I don't think is the right way to do it.

So currently I'm making a "chat application" with Scala and Akka where I use a separate client and server entity. The client connects to server, sends a message, and the server does something with it.

I got the sending a message working but now I'm stuck on reading the message server-side. Whenever I receive a message I get a ByteString containing the ASCII values of the characters from the message. How do I convert this ByteString into an actual String?

Relevant code (server-side):

package chatapp.server

import java.net.InetSocketAddress

import akka.actor.{Actor, ActorSystem}
import akka.io.Tcp._
import akka.io.{IO, Tcp}

* Created by Niels Bokmans on 30-3-2016.
class ServerActor(actorSystem: ActorSystem) extends Actor {
val Port = 18573
val Server = "localhost"

IO(Tcp)(actorSystem) ! Bind(self, new InetSocketAddress("localhost", Port))

def receive: Receive = {

case CommandFailed(_: Bind) =>
println("Failed to start listening on " + Server + ":" + Port)
context stop self

case Bound(localAddress: InetSocketAddress) =>
println("Started listening on " + localAddress)

case Connected(remote, local) =>
println("New connection!")
sender ! Register(self)
case Received(data) =>

Picture of server (as you can see it accepts connections -> receives a new connection -> receives a message from the connection):
Server side

Picture of client (connects to server and then sends message "testmessage")
Client side

Answer Source

You can use the decodeString method like this:

scala> val x = ByteString("abcd")
x: akka.util.ByteString = ByteString(97, 98, 99, 100)

scala> x.decodeString("US-ASCII")
res0: String = abcd
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download