现在我正在这样做: 客户端:(python)
data = json.dumps({"A":"PRINT","B":"ARTIFACTS","C":10})
s.send(data)
服务器端:(C ++)
recv(newSd, (char*)&msg, sizeof(msg), 0);
string str(msg);
string text = msg;
bool parsingSuccessful = reader.parse( text, root );
if ((root["A"] == "PRINT") &&
(root["B"]== "ARTIFACTS")&&
(root["C"]==10)){
PRINT(ARTIFICATS,10);
}
我知道这不是帮助我的正确方法。
谢谢。
答案 0 :(得分:6)
您可以使用unordered_map
实现从命令字符串到处理该命令的函数的实现的映射。
示例实现可以按如下方式工作:
// A function handler takes its arguments as strings and returns some sort of result
// that can be returned to the user.
using CommandHandler = std::function<Result(std::vector<std::string> const&)>
// various handers for command requests
Result handle_print(std::vector<std::string> const& args);
Result handle_delete(std::vector<std::string> const& args);
Result handle_add(std::vector<std::string> const& args);
Result handle_version(std::vector<std::string> const& args);
// the table that holds our commands
std::unordered_map<string, CommandHandler> command_table = {
{"print", handle_print},
{"delete", handle_delete},
{"add", handle_add},
{"version", handle_version},
};
// take your json doucment, extract the first value as the command, and put the rest into an arg array:
void handle_request(Connection& connection, json const& request)
{
std::string cmd = root["A"];
std::vector<std:string> args;
// parse the rest of your arguments into an array here.
if(command_table.count(cmd))
{
// command is valid
auto& handler = command_table[cmd];
auto result = handler(args);
send_result(connection, result);
}
else
{
// send bad command error or something
send_bad_command(connection);
}
}