Search code examples
scalaakka

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
      actorSystem.terminate()

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

    case Connected(remote, local) =>
      println("New connection!")
      sender ! Register(self)
    case Received(data) =>
      println(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


Solution

  • Use

    scala> val data = ByteString("xyz")
    data: akka.util.ByteString = ByteString(120, 121, 122)
    
    scala> data.utf8String
    res3: String = xyz
    

    see ByteString API,

    or on github:

    final def utf8String: String = decodeString(StandardCharsets.UTF_8)