想问一下使用socket实现http访问图片,读写过程应该是怎么样的?

这个是我写的实现传送图片的的过程,header成功传递,浏览器能读出文件大小,可是无法访问图片,是读写的过程出了问题吗?

void sendJPG(int *sock, char *filename) {
    int client_sock = *sock;
    char buffer[buffer_size];
    FILE *fp;
    FILE *fw;
    fp = fopen(filename, "rb");

    fseek(fp, 0L, SEEK_END);
    int len = ftell(fp);

    string status = "HTTP/1.1 200 OK\r\n";
    string header = "Server: A Simple Web Server\r\nContent-Type: image/jpeg\r\n";
    header += "Content-Range: bytes ";
    header += to_string(0);
    header += "-";
    header += to_string(len - 1);
    header += "/";
    header += to_string(len);
    header += "\r\n";
    header += "Content-Length: ";
    header += to_string(len);
    header += "\r\n\r\n";
    write(client_sock, status.c_str(), status.length());
    write(client_sock, header.c_str(), header.length());

    if (NULL == fp) {
        sendError(sock);
        close(client_sock);
        handleError("open file failed");
        return;
    }

    printf("Sending img\n");
    fw = fdopen(client_sock, "w");
    fread(buffer, sizeof(char), sizeof(buffer), fp);
    while (!feof(fp)) {
        fwrite(buffer, sizeof(char), sizeof(buffer), fw);
        fread(buffer, sizeof(char), sizeof(buffer), fp);
    }

    printf("Finish sending\n");

    fclose(fw);
    fclose(fp);
    close(client_sock);
}
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问