In short:
The main problem is, for an online game, server should support multiple types of action which client wants to do, such like: "Sign in game." , "Create a game room." , "Launch a game.", "send a chat message.", "Get a room list." ...
But if I'm going to use Socket, I'm wondering what is the best way to distinguish out the type of the action from each message received or sended between server and client.
This is what the deployment of my online game looks like:
For supporting multiple types of action, my first idea:
If I choose to use JSON, it might look like:
{
"action":"signIn",
"data":{
"id":"00001",
"name":"waterball"
}
}
and then the Server side can distinguish out the action by parsing the JSON property.
But a problem occurs, I will have lots of "if-else" descriptions like:
if ( action.equals("signIn") )
....
else if ( action.equals("createRoom") )
....
else if ( action.equals("launchGame") )
....
And the program can be very unscalable and unmaintainable.
So please share your idea about what is the better way to support multiple types of action between Server/Client socket.
Thanks.
But a problem occurs, I will have lots of "if-else" descriptions like:
You can define an Processing
interface with a process()
method that accepts a JSON object (for example : javax.json.JsonObject
).
Each action implements this interface.
In this way you can use a Map<String, Action>
that stores the Action subclass associated to each String action.
For example to initialize the map:
Map<String, Action> actionsByName = new HashMap<>();
actionsByName.put("signIn", new SignAction());
actionsByName.put("createRoom", new CreateRoomAction());
To handle the user action :
String actionName = ..;
Action action = actionsByName.get(actionName);
action.process(jsonObject);