scala 如何将 Akka ByteString 转换为 String?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36315667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert Akka ByteString into String?
提问by nbokmans
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.
如果这是一个愚蠢的问题,我很抱歉,但老实说,如果不设置某种 ASCII 代码 -> 自己的字符映射器,我无法弄清楚,我认为这不是正确的方法。
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.
所以目前我正在使用 Scala 和 Akka 制作一个“聊天应用程序”,我使用单独的客户端和服务器实体。客户端连接到服务器,发送一条消息,然后服务器用它做一些事情。
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?
我收到了发送消息的工作,但现在我一直在阅读消息服务器端。每当我收到一条消息时,我都会收到一个 ByteString,其中包含消息中字符的 ASCII 值。如何将此 ByteString 转换为实际的 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):

服务器图片(如您所见,它接受连接 -> 接收新连接 -> 接收来自连接的消息):

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

回答by Andrzej Jozwik
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:
或在 github 上:
final def utf8String: String = decodeString(StandardCharsets.UTF_8)
最终 def utf8String: String = decodeString(StandardCharsets.UTF_8)
回答by rgcase
You can use the decodeStringmethod like this:
你可以使用这样的decodeString方法:
scala> val x = ByteString("abcd")
x: akka.util.ByteString = ByteString(97, 98, 99, 100)
scala> x.decodeString("US-ASCII")
res0: String = abcd

