menacher/java-game-server

How to send events from player's session to game room's session?

yauhen-l opened this issue · 7 comments

Hi Abraham,

Could you please explain how to send events from player's session to game room's session?
You wrote:
The player session's listen on the Game Room session for any outgoing network data using event handlers.
The player sessions have a reference to their Game Room using a parentGameRoom variable and can send data to it using onEvent.

Do I understand correct that I have to do next steps in player's handler:

  1. Call getSession() to get player's session.
  2. Cast this session to PlayerSession.
  3. Call getParentGameRoom of this PlayerSession.
  4. Cast room to GameRoomSession.
  5. Call onEvent() of this GameRoomSession.

I think this should be a little easier:

  1. Call getSession() to get player's session.
  2. Call onEvent() of this session.
  3. GameRoomSession catches raised event and handles it.

In this case I have to add a custom handler to GameRoomSession.

Perhaps such a mechanism is already provided and I'm just inattentive?

I think if every event on session is also patched onto GameRoom then performance will degrade and its logic would get cluttered. What do you think?

I will add a send(Event event) method on the GameRoom interface, so whenever session wants to send something to gamerroom, it will have to invoke this method. This will remove step 4. I think if I use Generics on DefaultSessionEventHandler then the casting can be removed, saving one more step. Let me give it a try.
Inform me if you have any other idea.

Maybe we could declare additional event type, e.g. ROOM_SESSION_EVENT, and Room catches events only of that type?

We already have the event, SESSION_MESSAGE. Since GameRoom is also having a session it is easy to patch this event to the GameRoom. Issue here is the Session is listening to the Game Room event and Game Room will now listen to Session event, I am wondering if that is good design, where we have observer and observable both listening to each other cyclically. Could easily run into leaks(if handlers are not removed properly), message duplication in case we dont clear handlers when disconnecting and may be even recursive calls if not careful.
Or maybe its not a big deal, let me know what you think.

You are right. It could be dangerous.
I have another idea.
Could we declare extra method into PlayerSession with default implementation:
public boolean sendToRoom(Event у) {
if(this.getGameRoom() instanceof Session){
Session roomSession = (Session)this.getGameRoom();
roomSession.onEvent(e);
retrun true;
}
return false;
}

Yes. This makes sense, I will do the change and push.

Please checkout and let me know if it works for you.

Thanks.
It works fine.