【问题标题】:How to convert Akka ByteString into String?如何将 Akka ByteString 转换为字符串?
【发布时间】:2016-07-18 20:38:30
【问题描述】:

如果这是一个愚蠢的问题,我很抱歉,但如果不自己设置某种 ASCII 码 -> 字符映射器,我真的无法弄清楚,我认为这不是正确的方法。

所以目前我正在使用 Scala 和 Akka 制作一个“聊天应用程序”,其中我使用单独的客户端和服务器实体。客户端连接到服务器,发送一条消息,服务器用它做一些事情。

我可以发送消息,但现在我只能在服务器端阅读消息。每当我收到一条消息时,我都会得到一个 ByteString,其中包含消息中字符的 ASCII 值。如何将此 ByteString 转换为实际的字符串?

相关代码(服务器端):

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)
  }
}

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

客户端的图片(连接到服务器然后发送消息“testmessage”)

【问题讨论】:

    标签: scala akka


    【解决方案1】:

    您可以像这样使用decodeString 方法:

    scala> val x = ByteString("abcd")
    x: akka.util.ByteString = ByteString(97, 98, 99, 100)
    
    scala> x.decodeString("US-ASCII")
    res0: String = abcd
    

    【讨论】:

    • 请注意,这不会抛出指定编码的无效字节序列。例如,ByteString(192).decodeString(ByteString.UTF_8)
    【解决方案2】:

    使用

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

    见ByteString API,

    或在github上:

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

    【讨论】:

    • 这应该带有一些警告。它假定ByteString 包含完整的字符。如果它仅包含多字节字符的某些字节,则行为未指定(根据 String 的文档)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多