# How to keep the connection open to websocket server?

**URL:** <https://discuss.akka.io/t/how-to-keep-the-connection-open-to-websocket-server/3990>\
**Category:** Akka HTTP\
**Tags:** scala\
**Created:** [April 16, 2019, 11:35am UTC](https://discuss.akka.io/t/how-to-keep-the-connection-open-to-websocket-server/3990 "2019-04-16T11:35:28Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![bifunctor](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.akka.io/bifunctor/32/1335_2.png) [@bifunctor](https://discuss.akka.io/u/bifunctor)\
**Post date:** [April 16, 2019, 11:35am UTC](https://discuss.akka.io/t/how-to-keep-the-connection-open-to-websocket-server/3990/1 "2019-04-16T11:35:28Z")

</div>

Hi all

I have the following code, that does not keep the connection open to the websocket server:

```auto

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}.")
  }

}

```

So every time, when a message is received, it will close the connection and open a new connection for the next request.  
The question is, how can I keep the connection open?

Thanks

---

<div class="post-metadata">

**Author:** ![jrudolph](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.akka.io/jrudolph/32/80_2.png) [@jrudolph](https://discuss.akka.io/u/jrudolph)\
**Post date:** [April 23, 2019, 10:05am UTC](https://discuss.akka.io/t/how-to-keep-the-connection-open-to-websocket-server/3990/2 "2019-04-23T10:05:53Z")

</div>

Hi @bifunctor,

in brief, you can keep such a connection by using an `Source.actorRef` or `Source.queue`. `actorRef` directly materializes into an `ActorRef` that you can then use to send messages to the WS connection. `queue` will give you a queue-like interface to enqueue elements to be sent on the WS connection.

This might require a bit of fiddling to get the right materialized values out of the call to `singleWebSocketRequest` (right now you are throwing the materialized value away).

Johannes

---

<div class="post-metadata">

**Author:** ![bifunctor](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.akka.io/bifunctor/32/1335_2.png) [@bifunctor](https://discuss.akka.io/u/bifunctor)\
**Post date:** [April 26, 2019, 11:16am UTC](https://discuss.akka.io/t/how-to-keep-the-connection-open-to-websocket-server/3990/3 "2019-04-26T11:16:40Z")

</div>

Thanks a lot for your help.
