Is this possible in connection with C / C ++ communication?

I currently have a basic client / server setup. The server needs to receive requests from the client (s) and respond to different types of request messages. An example of a client request is a list of available files, the number of other clients connected to the server, etc.

I, obviously, would have to figure out a way to determine the type of message from the message received from the sender. I was wondering if I have a structure defined with the necessary data, then if I can overlay the structure on void *, send it as syscock, sockfd, message, length, flags, and not on the receiver side, return to the structure. This, of course, assumes that I am running the client and server in the same environment.

For example, if I have the following structure:

struct message {
   enum messageType { GET_FILES, GET_CLINET_NUMBER} messageType,
} 

and use this structure to send a message as follows

struct message msg;
msg.messageType = GET_FILES;
send(server_sockfd, (void*)&msg, sizeof(struct), 0)

and on the receiver

recv(,msg_buffer);
struct message received = (struct message*)msg_buffer;

Ignoring minor syntax issues, can anyone tell if this scheme is possible? If not, is there another way to send a message without sending raw char *?

+3
source share
3 answers

That's quite possible. It is not recommended, however, because now you are using the same environment for the client and server, but in the future you may change and you will have to change this code to be more platform / implementation independent.

Parameters? boost :: serialization, XML-RPC, even HTTP / REST or any other high-level protocol that suits you, Google protocol buffers, CORBA, etc.

+4
source

There are two things you should keep in mind:

  • Endianness. , , . x86, . , , , . , 0xdeadbeef, . , , .

  • Word. , , . , , . , :

    struct some_msg { long payload; };

    , 32- gcc/linux 64- gcc/linux? , 32- 4 . 64- 8 . .

, x86 , sparc, , 64-. 32- , , .

, , . , , typedefs, int32_t uint64_t. , , . .

+1

' struct void *, syscock, sockfd, message, length, flags), ' - . . , , , , , // , , TCP .

' , raw char *?' , (), strean, / , . / - , - , .

Rgds,

0
source

All Articles