我将演员用作接收器,如下所示:
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]
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) =>
// the Future[Done] is the materialized value of Sink.foreach
// and it is completed when the stream completes
val flow: Flow[Message, Message, Future[Done]] =
Flow.fromSinkAndSourceMat(incoming, Source.single(TextMessage(value)))(Keep.left)
// upgradeResponse is a Future[WebSocketUpgradeResponse] that
// completes or fails when the connection succeeds or fails
// and closed is a Future[Done] representing the stream completion from above
val (upgradeResponse, _) =
Http().singleWebSocketRequest(WebSocketRequest("ws://echo.websocket.org"), flow)
upgradeResponse.flatMap { upgrade =>
if (upgrade.response.status == StatusCodes.SwitchingProtocols) {
Future.successful(Done)
} else {
throw new RuntimeException(s"Connection failed: ${upgrade.response.status}")
}
}.andThen {
case Success(_) =>
log.info("Sending ACK")
sender() ! Ack
}.onComplete {
case Success(_) =>
log.info("Success proceed")
case Failure(ex) => log.error(ex.getMessage)
}
//sender() ! Ack
case Failed(ex) =>
log.info(s"Stream failed with ${ex.getMessage}.")
}
}
actor使用消息并进一步重定向到websocket服务器。
在代码中的某个地方,我向Ack
参与者发送了一个Sender
信号,表明它已准备好接收进一步的消息。但是,发送方参与者永远不会收到Ack
消息。
如果我将sender() ! Ack
放在FUTURE
链中,则它会按预期工作。
是否可以将sender() ! Ack
放在FUTURE`链中。
答案 0 :(得分:1)
尝试记住接收消息时的发件人,然后在代码中稍后使用它而不是sender()
而不是在下游调用sender(),这样该值在处理过程中可能不是恒定的(例如,当接收到消息中的其他消息时)同时,由于期货,您当前的任务没有阻止消息队列的处理)
case Msg(value) =>
val sender = sender()
.
.
sender ! Ack
答案 1 :(得分:1)
您的错误是以下几行:
}.andThen {
case Success(_) =>
log.info("Sending ACK")
sender() ! Ack
}.onComplete {
andThen
回调将由另一个线程执行,并且sender()
调用可能为空(相对幸运),甚至可能是另一个参与者在一起。您需要先捕获发送者,然后才能执行第一个异步操作。
val respondTo = sender()
upgradeResponse.flatMap { upgrade =>
if (upgrade.response.status == StatusCodes.SwitchingProtocols) {
Future.successful(Done)
} else {
throw new RuntimeException(s"Connection failed: ${upgrade.response.status}")
}
}.andThen {
case Success(_) =>
log.info("Sending ACK")
respondTo ! Ack
}.onComplete {
case Success(_) =>
log.info("Success proceed")
case Failure(ex) => log.error(ex.getMessage)
}