Reputation: 35
i am new in the socket programming in C/C++. I wrote Client and Server Socket. They can send and receive string. The idea is to send the commands to the server in the string. It can look something like this : "GET X" or "SET X 2". I know how i can split string. and the program know that the first word in the string is command, the second is attribute, and the third can be a value in case of SET-Command. My question is how i can say to programm that if it gets the string "GET X" it should call the function get(attribute). I thought the first about switch-case, but i think it's not a best solution for it. In case if it will be a lot of commands. THank you
Upvotes: 0
Views: 1796
Reputation: 3481
You can basically boil the problem down to the optimal way to map an operation name to the actual function being invoked, and whether or not solutions with better lookup characteristics are really needed.
O(n)
based solution (e.g. linear search) could be sufficient.O(log(n))
based approach (e.g. self-balancing binary trees) could be sufficient for more operations, as well.O(1)
lookup characteristics. However, that depends on a good hash function, which is itself not free in terms of cost.There are always time and space trade-offs involved. So its really best to profile before deciding on which approach is best for your application.
Regardless, these sorts of operation dispatch problems have been researched heavily. For example, here's one paper that discusses operation dispatch strategies in a CORBA C++ ORB implementation.
Besides optimizing operation lookup, you'll likely have to deal with other factors such as:
There are potentially many other problems you'll have to deal with on the client side as well. If at all possible, I'd recommend going with an existing RPC-like technology rather than reinvent the wheel yourself.
Upvotes: 1
Reputation: 75130
One way you could do it is have a lookup table of functions that you could call depending on the command which all returned a char*
, and send the response back to the client. You'd have to make a rudimentary hashing function of course.
Upvotes: 0
Reputation: 6480
I think it's best to use a switch statement.
If not you can use a map with the command string as key and a pointer to the callback function as a value.
Upvotes: 0