首页 > 解决方案 > 如何保存 websocket 客户端的连接并稍后使用 akka-streams 和 akka-http 发送

问题描述

我正在尝试遵循akka-http文档的这一部分,其中讨论了异步处理 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)
  }

}

我似乎无法弄清楚如何访问容器类型的aRequestContext或 a ?而当我在地图上的地图没有执行。UpgradeToWebSocketDirectivehttpResponse

标签: scalawebsocketakkaakka-streamakka-http

解决方案


推荐阅读