user3531196
user3531196

Reputation:

Unable to read all messages sent from client

I want to read all messages that are sent from the client. I am implementing a tcp server and it receives data. Each message is appended by the size of the message as a header. So Now I can read the header and find the size from that and allocate that much memory for the message to be read later. However, with my very little exposure to C++ this is what I came up with.

How to read all messages ?

 void *dothistask(void *socket_desc)
 {
   int sock = *(int*)socket_desc;
   free(socket_desc);
   int read_size;
   unsigned int x = 4;
   char *header = (char*)malloc(sizeof(char) * 4);
   char *message;
   int index = 0;
   long p;

   int status;
   while(true) {
     status = ReadXBytes(sock, 4, header);
     if(status == -1)
     {
        break;
     }
     message = (char *)malloc(sizeof(char) * 10);
     status = ReadXBytes(sock, 10, message);
     if(status == -1)
     {
        break;
     }
     cout<<"The header is "<<header<<endl;
     cout<<"The message is "<<message<<endl;
   }

  return 0;

 }

 int ReadXBytes(int socket, unsigned int x, void* buff)
 {
   char *buffer = (char*)buff;
   int bytesRead = 0;
   int result;
   while (bytesRead < x)
   {
     result = recv(socket, buffer + bytesRead, x - bytesRead, 0);
     if(result == 0)
     {
        cout<<"Client disconnected"<<endl;
        fflush(stdout);
        return -1;
     }
     else if( result == -1)
     {
        perror("recv failed");
        return -1;
     }
     bytesRead += result;
   }
   return 0;
 }

Read that it is ideal to read the header first and then read the message. I am able to do this once but I want to do this over a repeated period of time, basically forever, till the client disconnects.

Thank you! for the help!

Upvotes: 0

Views: 86

Answers (1)

Karsten Koop
Karsten Koop

Reputation: 2524

To read the message, you have

ReadXBytes(sock, 10, message);

but it should be something like

ReadXBytes(sock, *((int*)header), message);

depending on the content of header. As you have a hard-coded 10 in there, you will only ever read 10 bytes. You will also have to adjust the malloc accordingly to not only allocate 10 bytes.

Upvotes: 1

Related Questions