我試圖通過套接字將所有類型的文件發送到C++中的瀏覽器。我能夠發送。 txt
和.html
文件通過套接字很好,但是當我嘗試發送JPEG時,出現錯誤The image "localhost:8199/img.jpg" cannot be displayed because it contains errors
。我不知道爲什麼我的程序可以正常發送文本文件,但無法處理圖像。這是我讀文件,並將其寫入到客戶端:當在C++中通過套接字發送圖像時,「圖像無法顯示錯誤」
int fileLength = read(in, buf, BUFSIZE);
buf[fileLength] = 0;
char *fileContents = buf;
while (fileLength > 0) {
string msg = "HTTP/1.0 200 OK\r\nContent-Type:" + fileExt + "\r\n\r\n\r\nHere is response data";
int bytes_written;
if(vrsn == "1.1" || vrsn == "1.0"){
write(fd, msg.c_str(), strlen(msg.c_str()));
bytes_written = write(fd, fileContents, fileLength);
} else {
bytes_written = write(fd, fileContents, fileLength);
}
fileLength -= bytes_written;
fileContents += bytes_written;
}
全部代碼是在這裏:http://pastebin.com/vU9N0gRi
如果我查一下我的瀏覽器的網絡控制檯響應報頭,我看到Content-Type
是image/jpeg
所以我不確定我做錯了什麼。
圖像文件的處理方式與普通文本文件不同嗎?如果是這樣,爲了處理將圖像文件發送到瀏覽器,我必須做些什麼?
損壞頭和壞的長度(圖片不是字符串)。 –