Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 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 Reply

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...