如果我发送纯文本没有问题。一切都好。但是,如果我尝试从 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;
}