Akka HTTP Websocket,如何识别演员内部的连接

Akka HTTP Websocket, how to identify connections inside of actor

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

这是我的 WebsocketServer class

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)
    }
}

这是我的演员的简化代码,应该从 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 回复客户,但我仍然不知道如何:

我认为您需要某种 keyid 来映射您的连接角色。

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 中,删除 List 也更有效。

这个问题已经有人回答了。对于那里的 Java 人,这里是 java 版本:

public class WebsocketRoutes extends AllDirectives {

private final ActorSystem actorSystem;
private final ActorRef connectionManager;

public WebsocketRoutes(final ActorSystem actorSystem, final ActorRef connectionManager) {
    this.actorSystem = actorSystem;
    this.connectionManager = connectionManager;
}

public Route handleWebsocket() {
    return path(PathMatchers.segment(compile("router_v\d+")).slash(PathMatchers.segment("websocket")).slash(PathMatchers.segment(compile("[^\\/\s]+"))), (version, routerId) ->
            handleWebSocketMessages(createWebsocketFlow(routerId))
    );
}

private Flow<Message, Message, NotUsed> createWebsocketFlow(final String routerId) {

    final ActorRef connection = actorSystem.actorOf(WebsocketConnectionActor.props(connectionManager));

    final Source<Message, NotUsed> source = Source.<RouterWireMessage.Outbound>actorRef(5, OverflowStrategy.fail())
            .map((outbound) -> (Message) TextMessage.create(new String(outbound.message, "utf-8")))
            .throttle(5, FiniteDuration.create(1, TimeUnit.SECONDS), 10, ThrottleMode.shaping())
            .mapMaterializedValue(destinationRef -> {
                connection.tell(new RouterConnected(routerId, destinationRef), ActorRef.noSender());
                return NotUsed.getInstance();
            });

    final Sink<Message, NotUsed> sink = Flow.<Message>create()
            .map((inbound) -> new RouterWireMessage.Inbound(inbound.asTextMessage().getStrictText().getBytes()))
            .throttle(5, FiniteDuration.create(1, TimeUnit.SECONDS), 10, ThrottleMode.shaping())
            .to(Sink.actorRef(connection, PoisonPill.getInstance()));

    return Flow.fromSinkAndSource(sink, source);
}
}