简体   繁体   English

将图像从C#客户端发送到C服务器

[英]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. 但是,如果我尝试从C#客户端发送一个映像,服务器会收到正确的字节数,但是当我将缓冲区保存到文件(二进制模式 - wb)时,它总是有4个字节。

I send it by the C# client by using the function File.ReadAllBytes() . 我通过使用File.ReadAllBytes()函数由C#客户端发送它。

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) . 你初学者犯了使用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). 它不返回缓冲区中的字节数,而是返回指针的大小(如果运行32位或64位平台,则为4或8)。

You need to change the ReceiveMessage function to also "return" the size of the received data. 您需要更改ReceiveMessage函数以“返回”接收数据的大小。

Your C code needs to pass len back from the ReceiveMessage() function. 您的C代码需要从ReceiveMessage()函数传回len

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 . 你没有得到sizeof数组的sizeof Change to ie: 改为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 */
{


  ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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