Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

scala - 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

question from:https://stackoverflow.com/questions/36315667/how-to-convert-akka-bytestring-into-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...