gpt4 book ai didi

scala - Akka HTTP Websocket,如何识别actor内部的连接

转载 作者:行者123 更新时间:2023-12-04 14:55:51 26 4
gpt4 key购买 nike

我正在 Scala 中开发简单的多人游戏,我想通过 websockets 为 JS 客户端公开。

这是我的 WebsocketServer 类

class WebsocketServer(actorRef: ActorRef, protocol: Protocol, system: ActorSystem, materializer: ActorMaterializer) extends Directives {

val route = get {
pathEndOrSingleSlash {
handleWebSocketMessages(websocketFlow)
}
}

def websocketFlow: Flow[Message, Message, Any] =
Flow[Message]
.map {
case TextMessage.Strict(textMessage) => protocol.hydrate(textMessage)
}
.via(actorFlow)
.map(event => TextMessage.Strict(protocol.serialize(event)))


def actorFlow : Flow[Protocol.Message, Protocol.Event, Any] = {
val sink =
Flow[Protocol.Message]
.to(Sink.actorRef[Protocol.Message](actorRef, Protocol.CloseConnection()))

val source =
Source.actorRef[Protocol.Event](1, OverflowStrategy.fail)
.mapMaterializedValue(actor => actorRef ! Protocol.OpenConnection(actor))

Flow.fromSinkAndSource(sink, source)
}
}

这是我的 Actor 的简化代码,应该从 websocket 服务器接收消息。

class GameActor() extends Actor {

private var connections: List[ActorRef] = List()

override def receive: Receive = {

case message: Protocol.OpenConnection => {
this.connections = message.connection :: this.connections
message.connection ! Protocol.ConnectionEstablished()
}

case message: Protocol.CloseConnection => {
// how can I remove actor from this.connections ?
}

case message: Protocol.DoSomething => {
// how can I identify from which connection this message came in?
}
}
}

到目前为止一切顺利,目前我可以用简单的 WelcomeMessage 回复客户,但我仍然不知道如何:
  • 每当 actor 收到 CloseConnection 从连接列表中删除 actor信息?
  • 识别从哪个连接消息传到actor?
  • 最佳答案

    我认为你需要某种 keyid与您的连接 Actor 映射。

    def websocketFlow: Flow[Message, Message, Any] =
    val randomKey = Random.nextInt()
    Flow[Message]
    .map {
    case TextMessage.Strict(textMessage) => protocol.hydrate(textMessage)
    }
    .via(actorFlow(randomKey))
    .map(event => TextMessage.Strict(protocol.serialize(event)))


    def actorFlow(flowID: Int) : Flow[Protocol.Message, Protocol.Event, Any] = {
    val sink =
    Flow[Protocol.Message]
    .to(Sink.actorRef[Protocol.Message](actorRef, Protocol.CloseConnection(flowID)))

    val source =
    Source.actorRef[Protocol.Event](1, OverflowStrategy.fail)
    .mapMaterializedValue(actor => actorRef ! Protocol.OpenConnection(actor, flowID))

    Flow.fromSinkAndSource(sink, source)
    }

    然后在您的 Actor 中,您可以将连接存储在 Map 而不是 List 中,这也更有效地被删除。

    关于scala - Akka HTTP Websocket,如何识别actor内部的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40908964/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com