图像“ http://localhost:8882 /img.jpg”因为包含错误而无法显示
我正在尝试构建HTTP服务器,我使用相同的端口连接到浏览器,浏览器打开了一个.txt文件或目录,但是当我尝试打开图像时却收到上述消息,但我没有任何提示知道为什么
由于图像大小,我试图同时进行读写操作
int send_file_request(int fd, char *path,int content_length,int size)
{
int fd1;
char date[128];
char buf1[4000];
char *mime = get_mime_type(path);
char* request_shape="HTTP/1.0 200 OK\r\n"
"Server: webserver/1.0\r\n"
"Date: %s\r\n"
"Content-Type: %s\r\n"
"Content-Length: %ld\r\n"
"Connection: close\r\n\r\n%s";
char* request_shape_no_mime="HTTP/1.0 200 OK\r\n"
"Server: webserver/1.0\r\n"
"Date: %s\r\n"
"Content-Length: %ld\r\n"
"Connection: close\r\n\r\n";
int len=size+strlen(request_shape)+strlen(date)+100;
char*buf=malloc(len);
if(mime==NULL)
sprintf(buf,request_shape_no_mime, get_current_date(date, sizeof(date)), content_length);
else
sprintf(buf,request_shape, get_current_date(date, sizeof(date)), mime, content_length);
write_to_socket(fd,buf);
if ((fd1 = open(path, O_RDONLY)) == -1) {
perror("open error when transfer file");
}
int nread;
while ((nread = read(fd1, buf1, sizeof(buf1))) > 0) {
if (nwrite(fd, buf1, nread) <= 0) {
fprintf(stderr, "nwrite error when transfer file.\n");
return -1;
}
}
free(buf);
return 0;
}
nwrite函数
ssize_t nwrite(int fd, const void *buf, size_t count)
{
int nwrt;
const char *ptr = buf;
size_t nleft = count;
errno = 0;
while (nleft > 0) {
if ((nwrt = write(fd, ptr, nleft)) > 0) {
nleft -= nwrt;
ptr += nwrt;
} else if (nwrt == 0) {
fprintf(stderr, "connection has been closed.\n");
return 0;
} else {
if (errno == EINTR)
continue;
perror("write");
return -1;
}
}
return count;
}
浏览器应显示图像,但不显示