Question

I am in the process of writing a TCP server using Berkely SOCKET API under linux. Now the clients have a set of specifications and each message send by the client is based on those specifications i-e the message sent from the client corresponds to one of the many structs specified by the specs. Now the scenario is that the server doesn't know which message the client is going to send at what time. Once we get the message we can figure out what it is but not before that. The messages sent by the clients have variable lengths so we can not know in advance what message we are going to get. To solve this I have used the following method:

const char *buf[4096] = { 0 };
          if ( recv (connected, buf, 4096, 0) == -1)
             {
               printf ("Error in recvng message\n");
               exit (-1);
             }

That is I use a default buffer of size 4096 (no message from the client can be larger than this size). receive in that buffer and then afterwards I Check the message type and take the corresponding action as follows:

struct ofp_header *oph;
oph=(struct ofp_header *)buf;
switch (oph->type)
{
case example_pkt:
handle_example_pkt();
break;
}

This works fine but I just wanted to confirm that is it an appropriate method or is there something else that could be better than this. All help much appreciated.

Thanks.

Was it helpful?

Solution

TCP is stream-based. This means if you use a buffer larger than your message you may receive part of the next message as well.

This means you will need to know the size of the message and incorporate any additional data into the next message. There are two obvious ways to do this:

  1. Modify the protocol to send the size of each message as the first few bytes of the message. Read the size first, then only read that many bytes.

  2. Since you know the size of each message, keep track of how many bytes you read. Process the first message in the buffer then subtract the size of that message from the remaining bytes in the buffer. Continue to repeat this process until you either A. Don't have enough bytes left to identify the message type or B. Don't have enough bytes for a message of the detected type. Save any remaining bytes and call recv again to read more data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top