通过TCP/IP连接发送二进制文件

 傅雪莱_ 发布于 2022-12-23 18:07

我将在这里重述整个问题,以便它是可以回答的.

我能够在不使用套接字的同一台机器上完美地复制二进制文件,只是制作一个简单的复制功能.尝试实现此代码以复制到TCP/IP连接但无法使其工作.

FILE *filehandle = fopen("imagefile.jpg", "rb");
FILE *dest  =fopen("imagecopy.jpg", "wb");    // copied image file
fseek(filehandle, 0, SEEK_END);
unsigned long filesize = ftell(filehandle);
char *buffer = (char*)malloc(sizeof(char)*filesize);
rewind(filehandle);
int bytesread = fread(buffer, sizeof(char), filesize, filehandle);
for( int i=0; i

上面的代码非常适合在计算机中复制图像文件,但是当实现在服务器上复制时,很难实现.

我正在尝试将图像文件从服务器发送到客户端,这两个文件都是用C语言手动创建的.服务器发送的文件长度只有在服务器发送文件时才知道,因此缓冲区是动态的在服务器中生成,如下所示:

服务器

fseek(filehandle, 0, SEEK_END);
long filesize = ftell(filehandle);    // file could be 11000bytes
char *buffer = (char*)malloc(sizeof(char)*filesize);    // char buffer with 11000 bytes to store the data from the file.
// then I call the send() function
rewind(filehandle);    // go back to beginning
send(clientsocket, buffer, filesize, 0);    // this is being sent perfectly, no errors because in the actual code, I am checking for errors

客户

// here is where I don't understand how to dynamically allocate the 11000 bytes to store the data in a client buffer
// the filesize is not necessarily going to be 11000 so need to dynamically allocate
// I did the following:
#define BUFSIZE 10
FILE *filehandle = fopen("imagefile.jpg", "wb");    // image file created by client
char *buffer = (char*)malloc(sizeof(char)*BUFSIZE);
int bytesread = recv(buffer, 1, strlen(buffer), 0);
if( bytesread > 0 )
{
    printf("Bytes read: %d\n", bytesread);    // bytes read is 5
    printf("Buffer: %s\n", buffer);    // but buffer shows all the binary text like it normally would
    // when I try to store buffer in a file, it doesn't put full buffer because only 5 characters are written
    for( int i=0; i

如何动态分配服务器发送的11000字节?

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有