Reputation: 59
Now I'm doing like this: Client Side: (python)
data = json.dumps({"A":"PRINT","B":"ARTIFACTS","C":10})
s.send(data)
Server Side: (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);
}
I know this is not the correct way to do and help me out.
Thanks.
Upvotes: 0
Views: 110
Reputation: 2434
You can implement a map from the command string to the implementation of the function that handles that command using an unordered_map
.
An example implementation could work as follows:
// 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);
}
}
Upvotes: 6