为一个当前的项目,我需要以高效的方式实现自定义但预定义的网络协议,因为该软件将在不太小的多用户环境中运行。重要的是,协议处理本身非常快速,只有很小的开销,因此CPU和其他硬件可以完全用于服务器本身的工作。
我知道已经有类似问题的提问,但我认为我的问题有所不同。
让我展示一下我目前有两种不同的方法: 方法 1
在这种方法中,命令注册表已经从一开始就知道哪个执行器用于协议的哪个部分,所以我认为它不是非常动态,但我想这对我的需求来说已经足够了。
在这种方法中,只有
现在,我的问题是,在您诚实的意见中,哪种设计更好。回答问题时,请考虑设计和性能,因为两者对我来说都非常重要。
也许你甚至可以推荐一个更好的设计(同时也更有效率)?
// 编辑:
再次思考设计后,我找到了另一种基于外部库 "Netty" 的方法,我想要用于网络通信。
我打算为我想要处理的协议的每个部分编写
我知道已经有类似问题的提问,但我认为我的问题有所不同。
让我展示一下我目前有两种不同的方法: 方法 1
public class CommandRegistry {
private HashMap<String, HashSet<CommandExecutor>> mainHandlers = new HashMap<>();
public void registerMainHandler(CommandExecutor executor, String command) {
if (mainHandlers.get(command) == null) {
HashSet<CommandExecutor> executors = new HashSet<>();
executors.add(executor);
mainHandlers.put(command, executors);
} else {
HashSet<CommandExecutor> executors = mainHandlers.get(command);
executors.add(executor);
mainHandlers.remove(command);
mainHandlers.put(command, executors);
}
}
public void executeCommand(String command) {
for (CommandExecutor executor : mainHandlers.get(command)) {
executor.call();
}
}
}
CommandExecutor
类在这里将是抽象的,当然还有实现协议命令的子类。在这种方法中,命令注册表已经从一开始就知道哪个执行器用于协议的哪个部分,所以我认为它不是非常动态,但我想这对我的需求来说已经足够了。
public class CommandRegistry {
private List<CommandExecutor> executors = new ArrayList<>();
public void registerCommand(CommandExecutor executor) {
this.executors.add(executor);
}
public void callCommand(String command) {
for (CommandExecutor exec : executors) {
exec.callCommand(command);
}
}
}
public abstract class CommandExecutor {
List<String> myCommands;
public CommandExecutor(String... commands) {
this.myCommands = commands.toArray();
}
public void callCommand(String command) {
if (this.myCommands.contains(command)) {
this.executeCommandProcedure();
}
}
// This method contains the actual command procedure
protected abstract void executeCommandProcedure();
}
在这种方法中,只有
CommandExecutor
本身知道是否要处理命令。调用命令时,我们将遍历所有已注册的处理程序,并调用其中可能导致效率低下的方法。现在,我的问题是,在您诚实的意见中,哪种设计更好。回答问题时,请考虑设计和性能,因为两者对我来说都非常重要。
也许你甚至可以推荐一个更好的设计(同时也更有效率)?
// 编辑:
再次思考设计后,我找到了另一种基于外部库 "Netty" 的方法,我想要用于网络通信。
我打算为我想要处理的协议的每个部分编写
ChannelInboundHandlerAdapter
类,并将它们添加到 Netty 管道中。这样做会很有效,还是太昂贵了?
连接 -> 一些数据 -> 断开
,而且客户端和服务器之间还需要进行很多通信。 - Niklas S.