发送文件与插座 [英] Sending Files With Sockets
问题描述
我正在尝试创建一个基本的HTTP服务器,以了解更多有关它的工作原理。我有困难,发送二进制文件到客户端。我的代码如下:
char * buffer =(char *)malloc(sizeof(char)* 512);
fseek(content_file,0,SEEK_SET);
while(!feof(content_file)){
size_t read = fread(buffer,sizeof(char),sizeof(buffer),content_file);
if(read> 0){
client-> send((const void *)buffer);
}
}
fclose(content_file);
free(buffer);
现在我知道它可以发送一些不必要的数据,最后一个块读取之后,我想知道它有什么问题。它工作正常的文本文件,我使用的是fgets。但是在切换到fread以支持二进制文件后,文本文件已损坏,并且变成这样:这个是已发送数据中唯一正确的部分
(This p>
显然我错过了一些东西,但你能帮我正确地做到这一点吗?
编辑:
使用 buffer_size
值代替 sizeof(buffer)
你的问题是 sizeof(buffer)$ c $
添加一个 buffer_size
malloc
和已释放
。
I'm trying to create a basic HTTP server to learn more about how it works. I'm having difficulties with sending binary files to the client. My code is as below:
char * buffer = (char *)malloc(sizeof(char) * 512);
fseek(content_file, 0, SEEK_SET);
while (!feof(content_file)) {
size_t read = fread(buffer, sizeof(char), sizeof(buffer), content_file);
if (read > 0) {
client->send((const void *)buffer);
}
}
fclose(content_file);
free(buffer);
Now I know it can send some unnecessary data after the last block read but before trying to fix it, I want to know what's wrong with it. It was working fine for text files and I was using fgets. But after switching to fread to support binary files, text files are corrupted and became something like this: ThisÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ
("This" is the only correct part in the sent data)
Obviously I'm missing something but can you please help me to do this correctly?
Edit:
Using a buffer_size
value instead of sizeof(buffer)
fixed the missing/corrupted data problem.
You problem is that sizeof(buffer)
gives you the size of the pointer, not what it points to.
Add a buffer_size
and use that both for malloc
and freed
.
这篇关于发送文件与插座的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!