简体   繁体   English

Akka websocket 客户端:主动断开与服务器的连接和/或更换接收器

[英]Akka websocket client : actively disconnect from server and / or replace sink

I started to learn Akka and came across a challenge for which I can't find an easy solution, despite having waded through the documentation and related Stakoverflow questions:我开始学习 Akka 并遇到了一个我找不到简单解决方案的挑战,尽管我已经阅读了文档和相关的 Stakoverflow 问题:

Building on the Client-Side Websocket Support example on the Akka website, I am using as the basis the following code snippet in Scala:在 Akka 网站上的客户端 Websocket 支持示例上构建,我使用 Scala 中的以下代码片段作为基础:

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

  val (upgradeResponse, closed) =
  Http().singleWebSocketRequest(WebSocketRequest("ws://localhost/ws"), flow)

The use case I have is a client (printSink) consuming a continuous stream from the websocket server.我的用例是一个客户端(printSink)从 websocket 服务器消耗一个连续的 stream。 The communication uni-directional only, thus no need for a source.通信只是单向的,因此不需要源。

My question is then as follows:我的问题如下:

  1. I need to regularly force a re-connection to the websocket server, and for that I need to disconnect first.我需要定期强制重新连接到 websocket 服务器,为此我需要先断开连接。 But for the life of me, I can't find a way to do a simple disconnect但是对于我的生活,我找不到简单的断开连接的方法
  2. In a somewhat opposite scenario, I need to keep the websocket connection alive and "swap out" the sink.在稍微相反的情况下,我需要保持 websocket 连接处于活动状态并“更换”接收器。 Is this even possible, ie without creating another websocket connection?这是否可能,即无需创建另一个 websocket 连接?

For question 1 (forcing a disconnect from the client), this should work对于问题 1(强制断开与客户端的连接),这应该有效

val flow: Flow[Message, Message, (Future[Done], Promise[Option[Message])] =
  Flow.fromSinkAndSourceMat(
    printSink,
    Source.maybe
  )(Keep.both)

val (upgradeResponse, (closed, disconnect)) =
  Http().singleWebsocketRequest(WebSocketRequest("ws://localhost/ws"), flow)

disconnect can then be completed with a None to disconnect:然后可以使用None来完成disconnect连接:

disconnect.success(None)

For question 2, my intuition is that that sort of dynamic stream operation would seem to require a custom stream operator (ie one level below the Graph DSL and two levels below the "normal" scaladsl / javadsl ).对于问题 2,我的直觉是,这种动态 stream 操作似乎需要自定义 stream 运算符(即低于 Graph DSL 一级和低于“正常” scaladsl / javadsl )。 I don't have a huge amount of direct experience there, to be honest.老实说,我在那里没有大量的直接经验。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM