开发者

c socket send commands in string

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开发者_如何学C 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


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.

  • For a small number of functions a simple O(n) based solution (e.g. linear search) could be sufficient.
  • An O(log(n)) based approach (e.g. self-balancing binary trees) could be sufficient for more operations, as well.
  • Most folks jump straight to hash table based solution because of the theoretical 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:

  • Concurrency: is your application required to handle multiple connections from clients in parallel? Distributed concurrency is often very difficult to implement correctly.
  • Serialization: how will you send and receive data over-the-wire? Problems you could encounter include: sending plain text could be slow, numerical values may have to be converted to the receiving platforms endianness, your serialization protocols could change which would affect your users, etc.

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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜