发送文件与插座 [英] Sending Files With Sockets

查看:143
本文介绍了发送文件与插座的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个基本的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆