复合流会循环吗?

时间:2019-04-16 08:21:05

标签: scala akka akka-stream

我试图理解以下代码段的工作方式:

val flow: Flow[Message, Message, Future[Done]] =
      Flow.fromSinkAndSourceMat(printSink, helloSource)(Keep.left)

两个人对此thread进行了非常精彩的解释。我了解复合流的概念,但是它如何在websocket客户端上工作。

考虑以下代码:

import akka.actor.ActorSystem
import akka.{ Done, NotUsed }
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import akka.stream.scaladsl._
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.ws._

import scala.concurrent.Future

object SingleWebSocketRequest {
  def main(args: Array[String]) = {
    implicit val system = ActorSystem()
    implicit val materializer = ActorMaterializer()
    import system.dispatcher

    // print each incoming strict text message
    val printSink: Sink[Message, Future[Done]] =
      Sink.foreach {
        case message: TextMessage.Strict =>
          println(message.text)
      }

    val helloSource: Source[Message, NotUsed] =
      Source.single(TextMessage("hello world!"))

    // the Future[Done] is the materialized value of Sink.foreach
    // and it is completed when the stream completes
    val flow: Flow[Message, Message, Future[Done]] =
      Flow.fromSinkAndSourceMat(printSink, helloSource)(Keep.left)

    // upgradeResponse is a Future[WebSocketUpgradeResponse] that
    // completes or fails when the connection succeeds or fails
    // and closed is a Future[Done] representing the stream completion from above
    val (upgradeResponse, closed) =
      Http().singleWebSocketRequest(WebSocketRequest("ws://echo.websocket.org"), flow)

    val connected = upgradeResponse.map { upgrade =>
      // just like a regular http request we can access response status which is available via upgrade.response.status
      // status code 101 (Switching Protocols) indicates that server support WebSockets
      if (upgrade.response.status == StatusCodes.SwitchingProtocols) {
        Done
      } else {
        throw new RuntimeException(s"Connection failed: ${upgrade.response.status}")
      }
    }

    // in a real application you would not side effect here
    // and handle errors more carefully
    connected.onComplete(println)
    closed.foreach(_ => println("closed"))
  }
} 

这是一个websocket客户端,它将消息发送到websocket服务器,printSink接收并打印出来。

printSink会收到消息,SinkSource之间没有任何联系。

像循环吗?

enter image description here

流是从左到右流动的,Sink为何会消耗来自websocket服务器的消息?

1 个答案:

答案 0 :(得分:0)

Flow.fromSinkAndSourceMat将独立的SinkSource放在Flow的形状中。进入该Sink的元素不会在Source处结束。

从Websocket客户端API的角度来看,它需要一个Source,请求将从中发送到服务器,还需要一个Sink,它将响应发送到该服务器。 singleWebSocketRequest可以分别使用SourceSink,但这将是更加冗长的API。

这是一个较短的示例,它与您的代码段中的示例相同,但为runnable,因此您可以尝试一下:

import akka._
import akka.actor._
import akka.stream._
import akka.stream.scaladsl._

implicit val sys = ActorSystem()
implicit val mat = ActorMaterializer()

def openConnection(userFlow: Flow[String, String, NotUsed])(implicit mat: Materializer) = {
  val processor = Flow[String].map(_.toUpperCase)
  processor.join(userFlow).run()
}

val requests = Source(List("one", "two", "three"))
val responses = Sink.foreach(println)
val userFlow = Flow.fromSinkAndSource(responses, requests)

openConnection(userFlow)