简体   繁体   中英

Sending an image from a C# client to a C server

If I send plain text there is no problem. Everything is ok. However If I try to send from the C# client an image, the server receives correct bytes number, but when I save the buffer to a file (in binary mode - wb), it always has 4 bytes.

I send it by the C# client by using the function File.ReadAllBytes() .

My saving code looks like

   FILE * pFile;
   char *buf = ReceiveMessage(s);
   pFile = fopen (fileName , "wb");
   fwrite(buf, sizeof(buf[0]), sizeof(buf)/sizeof(buf[0]), pFile);
   fclose (pFile);
   free(buf);

My receiving function looks like

static unsigned char *ReceiveMessage(int s)
{
   int prefix;
   recv(s, &prefix, 4, 0);
   int len = prefix;
   char *buffer= (char*)malloc(len + 1);
   int received = 0, totalReceived = 0;
   buffer[len] = '\0';
   while (totalReceived < len)
   {
      if (len - totalReceived > BUFFER_SIZE)
      {
         received = recv(s, buffer + totalReceived, BUFFER_SIZE, 0);
      }
      else
      {
         received = recv(s, buffer + totalReceived, len - totalReceived, 0);
      }
      totalReceived += received;
   }

   return buffer;
}

You do a beginners mistake of using sizeof(buf) . It doesn't return the number of bytes in the buffer but the size of the pointer (which is four or eight depending on if you run 32 or 64 bit platform).

You need to change the ReceiveMessage function to also "return" the size of the received data.

Your C code needs to pass len back from the ReceiveMessage() function.

char *buf = ReceiveMessage(s);  // buf is a char*
... sizeof(buff)                // sizeof(char*) is 4 or 8

So you'll need something like

 static unsigned char *ReceiveMessage(int s, int* lenOut)
 {
     ...
     *lenOut = totalReceived ;
 }

You do not get size of array by sizeof . Change to ie:

int len = 0;
char *buf;

buf = ReceiveMessage(s, &len);

/* then use len to calculate write length */


static unsigned char *ReceiveMessage(int s, int *len) 
/* or return len and pass ptr to buf */
{


  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM