支持多种类型操作的客户端套接字和服务器套接字之间进行通信的最佳方式是什么?

What is the best way to communicate between client socket and server socket which suppors multiple types of action?

简而言之:

主要问题是,对于在线游戏,服务器应该支持客户端想要执行的多种类型的操作,例如:"Sign in game.","Create a game room." , "Launch a game.", "send a chat message.", "Get a room list." ...

但是如果我要使用 Socket,我想知道从服务器之间接收或发送的每条消息中区分操作类型的最佳方法是什么和客户。

这是我的在线游戏部署的样子:

为了支持多种类型的动作,我的第一个想法:

如果我选择使用 JSON,它可能看起来像:

{
    "action":"signIn",
    "data":{
        "id":"00001",
        "name":"waterball"
    }
}

然后Server端可以通过解析JSON 属性.

来区分出action

但是出现问题,我会有很多"if-else"这样的描述:

if ( action.equals("signIn") )
    ....
else if ( action.equals("createRoom") )
    ....
else if ( action.equals("launchGame") )
    ....

并且该程序可能非常不可扩展且不可维护。

因此,请分享您的想法,了解在 Server/Client 套接字之间支持多种类型操作的更好方法是什么。

谢谢。

我认为使用 JSON 是您的消息传递很好,但是,在处理多种类型的操作时,您可能对使用命令设计模式感兴趣。

https://www.tutorialspoint.com/design_pattern/command_pattern.htm

But a problem occurs, I will have lots of "if-else" descriptions like:

您可以使用接受JSON对象的process()方法定义Processing接口(例如:javax.json.JsonObject)。
每个动作都实现这个接口。
通过这种方式,您可以使用 Map<String, Action> 来存储与每个 String 操作关联的 Action 子类。

例如初始化地图:

Map<String, Action> actionsByName = new HashMap<>();
actionsByName.put("signIn", new SignAction());
actionsByName.put("createRoom", new CreateRoomAction());

处理用户操作:

   String actionName = ..;
   Action action = actionsByName.get(actionName);
   action.process(jsonObject);