尝试通过TCP连接传递字节时出错

时间:2018-08-06 12:55:51

标签: scala akka byte akka-stream

我需要通过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”作为整个字节传递?

1 个答案:

答案 0 :(得分:1)

您使用的Source工厂方法期望一个不变的Iterable。默认情况下,在数组上调用.toSeq会返回可变的Seq。解决此问题的一种方法是呼叫.toList

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