如何保持与Websocket服务器的连接打开?

时间:2019-04-16 11:36:12

标签: scala akka akka-stream

我有以下代码,无法保持与websocket服务器的连接打开:


import akka.Done
import akka.actor.{Actor, ActorLogging, Props}
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.ws.{Message, TextMessage, WebSocketRequest}
import akka.stream.{ActorMaterializer, Materializer}
import akka.stream.scaladsl.{Flow, Keep, Sink, Source}

import scala.concurrent._
import scala.util.{Failure, Success}

object WsActor {
  def props: Props = Props(new WsActor)
}

final class WsActor extends Actor with ActorLogging {

  import com.sweetsoft.WsConnector._

  implicit val materializer: Materializer = ActorMaterializer()
  implicit val ec: ExecutionContextExecutor = context.system.dispatcher
  implicit val actor = context.system

  // Future[Done] is the materialized value of Sink.foreach,
  // emitted when the stream completes
  private val incoming: Sink[Message, Future[Done]] =
  Sink.foreach[Message] {
    case message: TextMessage.Strict =>
      println(message.text)
    case _ =>
      println("Unknown messages.")
  }

  //private val outgoing: Source[Message, Promise[Option[Message]]] =
  //  Source.maybe[Message]

  //  val flow: Flow[Message, Message, Promise[Option[Message]]] =
  //    Flow.fromSinkAndSourceMat(incoming, Source.maybe[Message])(Keep.right)


  log.info("Websocket actor started.")

  override def receive: Receive = {
    case Initialized =>
      log.info("Initialization to receive messages via stream.")
      sender() ! Ack
    case Completed =>
      log.info("Streams completed.")
      sender() ! Ack
    case Msg(value) =>

      val replyTo = sender()
      val flow: Flow[Message, Message, Promise[Option[Message]]] =
        Flow.fromSinkAndSourceMat(incoming, Source.single(TextMessage(value)).concatMat(Source.maybe[Message])(Keep.right))(Keep.right)

      val (upgradeResponse, _) =
        Http().singleWebSocketRequest(WebSocketRequest("ws://127.0.0.1:7000/ws"), flow.mapAsync(4)(msg => Future(msg)))

      upgradeResponse.flatMap { upgrade =>
        if (upgrade.response.status == StatusCodes.SwitchingProtocols) {
          Future.successful(Done)
        } else {
          throw new RuntimeException(s"Connection failed: ${upgrade.response.status}")
        }
      }.onComplete {
        case Success(_) =>
          replyTo ! Ack
          log.info("Done")
        case Failure(ex) => log.error(ex.getMessage)
      }

    case Failed(ex) =>
      log.info(s"Stream failed with ${ex.getMessage}.")
  }

}

因此,每次收到消息时,它将关闭连接并为下一个请求打开新的连接。
问题是,如何保持连接打开?

1 个答案:

答案 0 :(得分:1)

Http().webSocketClientFlow代替Http().singleWebSocketRequest

Http().webSocketClientFlow将为您提供一个流程Flow[Message, Message, Future[WebSocketUpgradeResponse]]

这不会每次都创建新的连接。

您应该在伴随对象中声明它,以便该类的每个实例都可以使用相同的连接。

首先在单独的程序包中声明整个应用程序的actor系统。

object ActorEssentials {
        implicit val actorSystem = ActorSystem("test")
}

然后您可以声明以下内容

object WsActor {
  import ActorEssentials._
  def props: Props = Props[WsActor]
  val flow = Http()(actorSystem).webSocketClientFlow(...) 
}