从服务器关闭akka-http websocket连接

时间:2015-12-15 18:13:52

标签: scala akka-stream akka-http

在我的场景中,客户端发送“再见”websocket消息,我需要在服务器端关闭先前建立的连接。

来自akka-http docs

  

通过从服务器逻辑中取消传入连接流(例如,通过将其下游连接到Sink.cancelled,将其上游连接到Source.empty),可以实现关闭连接。也可以通过取消IncomingConnection源连接来关闭服务器的套接字。

但我不清楚如何做到这一点考虑到SinkSource在协商新连接时设置一次:

(get & path("ws")) {
  optionalHeaderValueByType[UpgradeToWebsocket]() {
    case Some(upgrade) ⇒
      val connectionId = UUID()
      complete(upgrade.handleMessagesWithSinkSource(sink, source))
    case None ⇒
      reject(ExpectedWebsocketRequestRejection)
  }
}

3 个答案:

答案 0 :(得分:4)

提示:此答案基于akka-stream-experimental版本2.0-M2。其他版本的API可能略有不同。

关闭连接的简便方法是使用PushStage

import akka.stream.stage._

val closeClient = new PushStage[String, String] {
  override def onPush(elem: String, ctx: Context[String]) = elem match {
    case "goodbye" ⇒
      // println("Connection closed")
      ctx.finish()
    case msg ⇒
      ctx.push(msg)
  }
}

在客户端或服务器端(通常是通过Flow的每个元素)接收的每个元素都经过这样的Stage组件。在Akka中,完整抽象被称为GraphStage,更多信息可以在official documentation中找到。

使用PushStage,我们可以查看具体的传入元素的值,并相应地转换上下文。在上面的示例中,一旦收到goodbye消息,我们就完成了上下文,否则我们只是通过push方法转发值。

现在,我们可以通过closeClient方法将transform组件连接到任意流:

val connection = Tcp().outgoingConnection(address, port)

val flow = Flow[ByteString]
  .via(Framing.delimiter(
      ByteString("\n"),
      maximumFrameLength = 256,
      allowTruncation = true))
  .map(_.utf8String)
  .transform(() ⇒ closeClient)
  .map(_ ⇒ StdIn.readLine("> "))
  .map(_ + "\n")
  .map(ByteString(_))

connection.join(flow).run()

上面的流程会收到ByteString并返回ByteString,这意味着它可以通过connection方法连接到join。在流程内部,我们首先将字节转换为字符串,然后再将它们发送到closeClient。如果PushStage没有完成流,则元素在流中被转发,在那里它被丢弃并被来自stdin的一些输入替换,然后通过网络发回。如果流完成,则将删除阶段组件之后的所有进一步流处理步骤 - 流现在已关闭。

答案 1 :(得分:3)

这可以通过akka-stream

的当前(2.4.14)版本中的以下内容来完成
"1/1/19"

使用它来定义你的舞台

TextBox

然后将其作为流程的一部分包含在内

package com.trackabus.misc

import akka.stream.stage._
import akka.stream.{Attributes, FlowShape, Inlet, Outlet}

// terminates the flow based on a predicate for a message of type T
// if forwardTerminatingMessage is set the message is passed along the flow
// before termination
// if terminate is true the stage is failed, if it is false the stage is completed
class TerminateFlowStage[T](
    pred: T => Boolean, 
    forwardTerminatingMessage: Boolean = false, 
    terminate: Boolean = true)
  extends GraphStage[FlowShape[T, T]]
{
  val in = Inlet[T]("TerminateFlowStage.in")
  val out = Outlet[T]("TerminateFlowStage.out")
  override val shape = FlowShape.of(in, out)

  override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = 
    new GraphStageLogic(shape) {

      setHandlers(in, out, new InHandler with OutHandler {
        override def onPull(): Unit = { pull(in) }

        override def onPush(): Unit = {
          val chunk = grab(in)

          if (pred(chunk)) {
            if (forwardTerminatingMessage)
              push(out, chunk)
            if (terminate)
              failStage(new RuntimeException("Flow terminated by TerminateFlowStage"))
            else
              completeStage()
          }
          else
            push(out, chunk)
        }
      })
  }
}

答案 2 :(得分:1)

另一种方法是使用Source.queue中的队列管理连接。队列可用于向客户端发送消息以及关闭连接。

def socketFlow: Flow[Message, Message, NotUsed] = {
  val (queue, source) = Source.queue[Message](5, OverflowStrategy.fail).preMaterialize()

  // receive client message 
  val sink = Sink.foreach[Message] {
    case TextMessage.Strict("goodbye") =>
      queue.complete() // this closes the connection
    case TextMessage.Strict(text) =>
      // send message to client by using offer
      queue.offer(TextMessage(s"you sent $text")) 
  }
  Flow.fromSinkAndSource(sink, source)
}

// you then produce the upgrade response like this
val response = upgrade.handleMessages(socketFlow)

将队列用于WebSocket的好处是,只要有访问权限,就可以使用它在任何时候发送消息,而不必等待传入的消息答复。