如何保存websocket客户端的连接并稍后通过akka-streams和akka-http发送

时间:2018-06-28 21:21:49

标签: scala websocket akka akka-stream akka-http

我正在尝试遵循akka-http documentation的这一部分,该部分讨论异步处理Web套接字消息

我要这样做的是:

  1. 接收对客户端的websocket请求
  2. 将付款发票发回给客户
  3. 运行一个后台进程,该进程保存了客户的websocket连接,当客户支付发票时,在这种情况下,将他们查询的数据发送回去(“世界”)。

这是我到目前为止的代码

def hello: Route = {
  val amt = 1000
  val helloRoute: Route = pathPrefix(Constants.apiVersion) {
  path("hello") {
    val source: Source[Message, SourceQueueWithComplete[Message]] = {
      Source.queue(1, OverflowStrategy.backpressure)
    }

    val paymentRequest = createPaymentRequest(1000, extractUpgradeToWebSocket)
    Directives.handleWebSocketMessages(
      paymentFlow(paymentRequest)
    )
    }
  }
  helloRoute
}

private def createPaymentRequest(amt: Long, wsUpgrade: Directive1[UpgradeToWebSocket]) = {
    val httpResponse: Directive1[HttpResponse] = wsUpgrade.map { ws =>
      val sink: Sink[Message, NotUsed] = Sink.cancelled()
      val source: Source[Message, NotUsed] = Source.single(TextMessage("World"))
      val x: HttpResponse = ws.handleMessagesWithSinkSource(sink, source)
      x
    }
    httpResponse.map { resp =>
      //here is where I want to send a websocket message back to the client
      //that is the HttpResponse above, how do I complete this? 
      Directives.complete(resp)
  }

}

我似乎无法弄清楚如何在容器类型RequestContext之外访问UpgradeToWebSocketDirective?当我在httpResponse上映射时,该映射未执行。

0 个答案:

没有答案