1

如果我发送纯文本没有问题。一切都好。但是,如果我尝试从 C# 客户端发送图像,服务器会收到正确的字节数,但是当我将缓冲区保存到文件(二进制模式 - wb)时,它总是有 4 个字节。

我通过 C# 客户端使用函数发送它File.ReadAllBytes()

我的保存代码看起来像

   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);

我的接收功能看起来像

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;
}
4

3 回答 3

1

您在使用sizeof(buf). 它不返回缓冲区中的字节数,而是返回指针的大小(取决于您运行 32 位还是 64 位平台,为 4 或 8)。

您需要更改ReceiveMessage函数以“返回”接收数据的大小。

于 2012-04-13T14:35:42.873 回答
1

您的 C 代码需要len从 ReceiveMessage() 函数传回。

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

所以你需要类似的东西

 static unsigned char *ReceiveMessage(int s, int* lenOut)
 {
     ...
     *lenOut = totalReceived ;
 }
于 2012-04-13T14:35:49.657 回答
1

你没有得到数组的大小sizeof。更改为即:

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 */
{


  ...
}
于 2012-04-13T14:42:29.437 回答