在Scala中关闭套接字上的Akka HTTP WebSocket事件

时间:2018-06-08 14:07:46

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

我正在使用Scala和Akka HTTP。

我有一个基于Akka HTTP的服务器后端应用程序。传入的WebSocket消息由handleWebSocketMessages处理:

/**
  * Route for WebSocket request
  */
private val webSocketRoute: Route = pathSuffix(Constants.WSPROXY_WEBSOCKET_PATH_SUFFIX) {
    LOGGER.debug("() Web socket route")
    handleWebSocketMessages(wsRouteImpl)
}

/**
  * This method calls all registered handlers.
  *
  * @return flow for handleWebSocketMessages method
  */
private def wsRouteImpl: Flow[Message, Message, Any] = {
    LOGGER.debug("() wsRouteHandling")
    numOfClients += 1

    LOGGER.info(s"Client has connected, current number of clients: $numOfClients")

    var flow = Flow[Message].mapConcat {
  // Call specific handlers depending on message type
  ...
}

我的WebSocket客户端与keep-alive建立双向通信连接。

绑定完成:

val binding = Http().bindAndHandle(webSocketRoute, config.host, config.port)

问题是我需要为已关闭的套接字注入回调(例如,如果客户端已断开连接)并减少当前的客户端数量,但我找不到任何入口点。

是否可以在套接字关闭时捕获某种事件?

1 个答案:

答案 0 :(得分:3)

使用watchTermination

val numOfClients = new java.util.concurrent.atomic.AtomicInteger(0)

private val webSocketRoute: Route = pathSuffix(Constants.WSPROXY_WEBSOCKET_PATH_SUFFIX) {
  LOGGER.debug("() Web socket route")

  val wsFlow: Flow[Message, Message, Any] =
    wsRouteImpl.watchTermination() { (_, fut) =>
      numOfClients.incrementAndGet()
      LOGGER.info(s"Client has connected. Current number of clients: $numOfClients")

      fut onComplete {
        case Success(_) =>
          numOfClients.decrementAndGet()
          LOGGER.info(s"Client has disconnected. Current number of clients: $numOfClients")
        case Failure(ex) =>
          numOfClients.decrementAndGet()
          LOGGER.error(s"Disconnection failure (number of clients: $numOfClients): $ex")
      }
    }

  handleWebSocketMessages(wsFlow)
}

private def wsRouteImpl: Flow[Message, Message, Any] = ???