[英]Client-server app command pattern
我正在编写一个客户端服务器应用程序,但是在使用命令模式时遇到了问题。 在我的程序服务器中,从客户端接收String输入命令,在HashMap中为输入找到合适的命令,执行该命令并发回返回值。 我在弄清楚如何编写需要超过1个步骤的命令时遇到了问题(命令必须询问客户额外的参数,然后应返回最终结果)。
命令界面
public interface Command {
public String execute();
}
与客户端的服务器通信
try {
ServerSocket serverSocket = new ServerSocket(port);
Command c;
while(true) {
Socket clientSocket = serverSocket.accept();
PrintWriter clientSocketWriter = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader clientSocketReader = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
String inputLine;
//server recieves String command from client and sends back the result while semaphore is true
while (Main.semaphore) {
inputLine = clientSocketReader.readLine();
c = CommandFactory.getCommandByName(inputLine);
clientSocketWriter.println(c.execute());
}
serverSocket.close();
clientSocketWriter.close();
clientSocketReader.close();
clientSocket.close();
}
} catch(Exception e) {
e.printStackTrace();
}
一步命令没有问题
public class CommandHelp implements Command {
@Override
public String execute() {
//returns string of all commands
return CommandFactory.getCommandByNames();
}
我不知道如何编写命令,该命令需要额外的执行指令,无法在不知道结果的情况下立即返回结果。 命令应返回x个元素的排列数量(客户端应选择)。
public class CommandPermutationsCount implements Command {
@Override
public String execute() {
//can't return anything yet
}
public long getPermutations(int elementsCount) {
long result = 1;
for (int factor = 2; factor <= elementsCount; factor++) {
result *= factor;
}
return result;
}
}
我有一个使Command代替String无效的想法,但是那样我将无法通过clientSocketWriter发送与客户端的通讯。 有什么好方法可以执行更多步骤的命令?
我认为您的路线正确。 为什么不允许命令标识符及其参数在一行中传递? 我在想类似的东西:
>> permute -a 12
>> shuffle -a [1, 2, 7, 6, 5, 3, 1]
>> add -a 4 -a 5
通过允许使用参数指定的命令,您的CommandFactory
变为:
class CommandFactory {
public static Command parseCommand(String commandLine) {
// Tokenize commandLine:
// - First word is commandId
// - Tokens following '-a' string are arguments
// Return CommandHelp if no command with provided commandId is found
return CommandHelp(commandLine);
}
}
现在,您可以创建从抽象的Command
类继承的特定命令实现,如下所示:
abstract class Command {
private final String commandId;
private final String commandArguments;
Command(String commandId, List<String> commandArguments) {
this.commandId = commandId;
this.commandArguments = commandArguments;
}
abstract String execute();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.