I am working on a simple mulitplayer game in scala which I would like to open via websockets for JS clients.
Here is my 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) } }
This is the simplified code of my actor, which should receive messages from the websocket server.
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? } } }
So far, so good that I can currently respond with a simple WelcomeMessage client, but I still don't know how:
- remove a member from the connection list whenever an actor receives a
CloseConnection message? - identify which message connected to the actor?
source share