首页 > 解决方案 > 尝试通过 TCP 连接传递字节时出错

问题描述

我需要通过 tcp 连接传递像“0x02”这样的字节并在服务器上处理它。客户端代码在这里:

package protocol
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Source, Tcp}
import akka.util.ByteString
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Source, Tcp}
import akka.util.ByteString
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}

class UpperServiceClient(ip: String, port: Int) {
    def run = {
        implicit val system = ActorSystem("ClientSys")
        implicit val materializer = ActorMaterializer()

        val a1 = Array("0x02", "0x02").toSeq
        val testInput = a1.map(ByteString(_))
        val result: Future[ByteString] = Source(testInput).via(Tcp().outgoingConnection(ip, port)).
          runFold(ByteString.empty) { (acc, in) => acc ++ in }

        val res: ByteString = Await.result(result, 10.seconds)
    }
}

但 IDEA 向我显示错误:

类型不匹配,预期:Iterable[NotInferedT],实际:Seq[ByteString]

我应该怎么做才能将“0x02”作为整个字节传递?

标签: scalaakkabyteakka-stream

解决方案


您正在使用的Source工厂方法需要一个不可变的Iterable. 默认情况下,调用.toSeq数组会返回一个 mutable Seq。解决此问题的一种方法是改为调用.toList

val a1 = Array("0x02", "0x02").toList

推荐阅读