复合流会产生循环吗?

Does composite flow make loop?

我试图了解以下代码片段的工作原理:

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

两个大佬对这个给出了非常精彩的解释。我了解复合流的概念,但它如何在 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之间没有联系。

像循环吗?

流是从左到右的,Sink是怎么消费websocket服务器消息的?

Flow.fromSinkAndSourceMat 将一个独立的 Sink 和一个 Source 放在 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)