Network functions

Started by
5 comments, last by hplus0603 18 years, 1 month ago
I can't think of a good way of sending commands from my client to my server. I have one idea, but it isn't a very good way of going about this.. heres an example: The client sends a message(a string) to the server that reads "messagebox" and the server has a recv function like: recv(sd, buf, sizeof(buf), 0); if(buf == "messagebox") { messagebox(...); }else{ cout<<"Unknown command"; } I am looking for a nice way of creating commands to send over the network without the commands being if(string = cmd) type statements. Any insight on how I could do a command system not based on text and execution on hte client side?
Hello?
Advertisement
switch(code){ ...}


Make the first four bytes (or whatever) of each message an integer that defines the action.

Also, if this is TCP, remember you need to mark where in the stream to split into messages; it doesn't guarantee that what you send in one call to send() will arrive in one call to recv(). If you're using UDP you can ignore this (but remember your data may not arrive at all).
I am no network expert,
but why dont you use a message system like windows for example

void Message(UINT messageid, int param1 int param2)

like this you dont have to use strings, which would increase performance.

once again i am complete noob, but maybe maybe i could help you ; )
cherio Woltan
If all you want is a system not based on text comparison then you can just use predefined constants instead of strings.

(Using simplified versions of the functions send and recv)

enum COMMAND{    NO_COMMAND,    CMD_MESSAGEBOX,    CMD_SOMECOMMAND,    CMD_SOMEOTHERCOMMAND,};void send_command(){   int cmd=CMD_MESSAGEBOX;   send(&cmd,sizeof(cmd));}void recv_command(){   int cmd=NO_COMMAND;   recv(&cmd,sizeof(cmd));   switch (cmd)   {   case CMD_MESSAGEBOX:      //Handle messagebox command      break;   case CMD_SOMECOMMAND:      //Handle somecommand command      break;   case CMD_SOMEOTHERCOMMAND:      //Handle someothercommand command      break;   default:      //Handle unknown command      break;   }}
Typically you use a byte or two preceeding the data to tell the other end what kind of data it is. On the other end you would use a switch statement to differentiate between the label bytes.
Depending on exactly how much control you need you might also want to look into Remote Procedure Calls (RPC). RPC's whole reason for existing is to be able to call functions on another computer in a pseudo-transparent manner. It's not really suitable for real-time guys but it fits your original example neatly.
-Mike
The Etwork networking library makes it easy to send and receive commands. It takes care of the tokenization for you (i e, the TCP-is-a-stream-not-a-message problem).
enum Bool { True, False, FileNotFound };

This topic is closed to new replies.

Advertisement