Scala 从服务器关闭akka http websocket连接
在我的场景中,客户机发送“再见”websocket消息,我需要关闭以前在服务器端建立的连接 从akka http: 通过从服务器逻辑中取消传入连接流(例如,将其下游连接到Sink.cancelled,将其上游连接到Source.empty),可以关闭连接。也可以通过取消IncomingConnection源连接来关闭服务器的套接字 但考虑到在协商新连接时,Scala 从服务器关闭akka http websocket连接,scala,akka-stream,akka-http,Scala,Akka Stream,Akka Http,在我的场景中,客户机发送“再见”websocket消息,我需要关闭以前在服务器端建立的连接 从akka http: 通过从服务器逻辑中取消传入连接流(例如,将其下游连接到Sink.cancelled,将其上游连接到Source.empty),可以关闭连接。也可以通过取消IncomingConnection源连接来关闭服务器的套接字 但考虑到在协商新连接时,Sink和Source只设置了一次,我不清楚如何执行此操作: (get & path("ws")) { optionalHeade
Sink
和Source
只设置了一次,我不清楚如何执行此操作:
(get & path("ws")) {
optionalHeaderValueByType[UpgradeToWebsocket]() {
case Some(upgrade) ⇒
val connectionId = UUID()
complete(upgrade.handleMessagesWithSinkSource(sink, source))
case None ⇒
reject(ExpectedWebsocketRequestRejection)
}
}
提示:此答案基于akka stream实验版
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)
}
}
在客户端或服务器端接收的每个元素(以及通常通过流
的每个元素)都通过这样的阶段
组件。在Akka中,完整的抽象称为GraphStage
,更多信息可以在中找到
使用PushStage
我们可以观察具体的传入元素的值,然后相应地转换上下文。在上面的例子中,一旦收到再见
消息,我们就完成了上下文,否则我们就通过推送
方法转发值
现在,我们可以通过transform
方法将closeClient
组件连接到任意流:
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
,这意味着它可以通过join
方法连接到connection
。在流内部,我们首先将字节转换为字符串,然后再将它们发送到closeClient
。如果PushStage
没有完成流,元素将在流中转发,在流中它将被丢弃并替换为来自stdin的一些输入,然后通过线路发送回。如果流已完成,则阶段组件之后的所有进一步流处理步骤将被删除-流现在已关闭。这可以通过当前(2.4.14)版本的akka流中的以下步骤来完成
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)
}
})
}
}
用它来定义你的舞台
val termOnKillMe = new TerminateFlowStage[Message](_.isInstanceOf[KillMe])
然后将其作为流程的一部分
.via(termOnKillMe)
另一种方法是使用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队列的一个好处是,您可以随时使用它发送消息,只要您有权访问它,而不必等待收到的消息回复。非常感谢!看起来像我一直在寻找的东西。不幸的是,当应用于“in”流时,这并没有关闭websocket连接(在akka http上)。也许它还需要将“out”源代码设置为
finish
ed。是的,akka http确实会在它们都“finish”时关闭连接:Flow
-通过finish
按建议对其进行处理,以及源代码
(输出)停止其底层参与者。