使用C服务器通过Internet发送大文件(图像)

时间:2014-02-10 16:53:51

标签: c image web-services http web

我正在使用套接字在C中创建一个简单的Web服务器,它侦听端口10001;到目前为止它工作正常,当我使用http://127.0.0.1:10001/时,我可以在浏览器中加载所有图像。但是当我尝试在网站上访问它时,所有大于4kb的图像都不会显示,当我单独打开它时,它只显示图像的1/3左右。

我有一个名称服务器将流量重定向到我的路由器80端口,然后将其转发到我本地计算机上的端口10001。

文件会像这样发送(在本例中为jpeg图像):

FILE *fp;
char *buf, header[1024];
int fsize, hsize, nbytes;
struct tm *itime;
time_t rawtime;

fp = fopen(file, "r");

fseek(fp, 0, SEEK_END);
fsize = ftell(fp);
rewind(fp);

time(&rawtime);
itime = localtime(&rawtime);

hsize = sprintf(header, "HTTP/1.1 200 OK\r\n"
                        "Server: iserv\r\n"
                        "Date: %s"
                        "Content-Length: %d\r\n"
                        "Content-Type: image/jpeg\r\n"
                        "Accept-Ranges: bytes\r\n"
                        "Connection: keep-alive\r\n\r\n", asctime(itime), fsize);

write(fd, header, hsize);

buf = (char*)malloc(CHUNK_SIZE);
while((nbytes = fread(buf, sizeof(char), CHUNK_SIZE, fp)) > 0)
    write(fd, buf, nbytes);

free(buf);

为什么会出现此问题,我该如何解决?

1 个答案:

答案 0 :(得分:1)

您的write()没有写出整个数据,因为您的套接字设置为非阻塞且您没有检查写入的数量。最简单的解决方法是使用O_NONBLOCK清除fcntl(fd, FSET_FL ...)

相关问题