协议切换成功与否
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了协议切换成功与否相关的知识,希望对你有一定的参考价值。
我有以下代码片段,不编译:
import akka.actor.ActorSystem
import akka.Done
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import akka.stream.scaladsl._
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.ws._
import scala.concurrent._
import scala.concurrent.duration._
object Main extends App {
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
import system.dispatcher
// Future[Done] is the materialized value of Sink.foreach,
// emitted when the stream completes
val incoming: Sink[Message, Future[Done]] =
Sink.foreach[Message] {
case message: TextMessage.Strict =>
println(message.text)
}
// flow to use (note: not re-usable!)
val sourceSocketFlow = RestartSource.withBackoff(
minBackoff = 3.seconds,
maxBackoff = 30.seconds,
randomFactor = 0.2,
maxRestarts = 3
) { () =>
Source.tick(2.seconds, 2.seconds, TextMessage("Hello world!!!"))
.viaMat(Http().webSocketClientFlow(WebSocketRequest("ws://127.0.0.1:8080/")))(Keep.right)
}
// the materialized value is a tuple with
// upgradeResponse is a Future[WebSocketUpgradeResponse] that
// completes or fails when the connection succeeds or fails
// and closed is a Future[Done] with the stream completion from the incoming sink
val (upgradeResponse, closed) =
sourceSocketFlow
.toMat(incoming)(Keep.both) // also keep the Future[Done]
.run()
// just like a regular http request we can access response status which is available via upgrade.response.status
// status code 101 (Switching Protocols) indicates that server support WebSockets
val connected = upgradeResponse.flatMap { upgrade =>
if (upgrade.response.status == StatusCodes.SwitchingProtocols) {
Future.successful(Done)
} else {
throw new RuntimeException(s"Connection failed: ${upgrade.response.status}")
}
}
connected.onComplete(println)
closed.foreach(_ => println("closed"))
}
这里的问题是:
// the materialized value is a tuple with
// upgradeResponse is a Future[WebSocketUpgradeResponse] that
// completes or fails when the connection succeeds or fails
// and closed is a Future[Done] with the stream completion from the incoming sink
val (upgradeResponse, closed) =
sourceSocketFlow
.toMat(incoming)(Keep.both) // also keep the Future[Done]
.run()
不会在元组的第一个位置返回Future[WebSocketUpgradeResponse]
,而是返回NotUsed
。
问题是,如何获得返回类型Future[WebSocketUpgradeResponse]
来识别连接是否成功。
答案
RestartSource#withBackoff接受sourceFactory
类型的() => Source[T, _]
并返回Source[T, NotUsed]
类型的新来源。因此,无法从包装的源中提取实现值。这可能是因为每次RestartSource重启时物化值都会有所不同。
问题是,如何获得返回类型Future [WebSocketUpgradeResponse]来识别连接是否成功。
如果要检查连接是否已建立,以及WebSockets握手是否成功,则可以使用Source#preMaterialize预先实现源。稍微修改过的代码版本如下所示:
val sourceSocketFlow: Source[Message, NotUsed] = RestartSource.withBackoff(
minBackoff = 3.seconds,
maxBackoff = 30.seconds,
randomFactor = 0.2,
maxRestarts = 3
) { () =>
val (response, source) = Source
.tick(2.seconds, 2.seconds, TextMessage("Hello world!!!"))
.viaMat(Http().webSocketClientFlow(WebSocketRequest("ws://mockbin.org/bin/82b160d4-6c05-4943-908a-a15122603e20")))(Keep.right).preMaterialize()
response.onComplete {
case Failure(e) ⇒
println(s"Connection failed")
case Success(value) ⇒
if (value.response.status == StatusCodes.SwitchingProtocols) {
println("Server supports websockets")
} else {
println("Server does not support websockets")
}
}
source
}
如果连接失败,或websocket handshake fails,您不必做任何事情。这两种情况都将由RestartSource处理。
以上是关于协议切换成功与否的主要内容,如果未能解决你的问题,请参考以下文章
http协议的状态码——400,401,403,404,500,502,503,301,302等常见网页错误代码