关于 scala:复合流是否会产生循环?

Does composite flow make loop?

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

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

两个人在这个线程上给出了非常精彩的解释。我了解复合流的概念,但它是如何在 websocket 客户端上工作的。

考虑以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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

Stream流是从左到右的,Sink怎么会消费来自websocket服务器的消息呢?


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

结束

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

这是一个较短的示例,它演示了与您的代码片段相同但可运行的示例,因此您可以使用它:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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)