- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在尝试通过套接字将所有类型的文件发送到 C++ 中的浏览器。我可以通过套接字发送 .txt
和 .html
文件,但是当我尝试发送 jpeg 时,出现错误 The image "localhost :8199/img.jpg"无法显示,因为它包含错误
。我不确定为什么我的程序可以很好地发送文本文件但不能处理图像。这是我读取文件并将其写入客户端的方式:
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
如果我在我的浏览器网络控制台中检查响应 header ,我看到 Content-Type
是 image/jpeg
所以我不确定我做错了什么.
图像文件的处理方式是否与普通文本文件不同?如果是这样,我究竟需要做什么才能将图像文件发送到浏览器?
最佳答案
string msg = "HTTP/1.0 200 OK\r\nContent-Type:" + fileExt + "\r\n\r\n\r\nHere is response data";
这是对二进制数据(如图像)的无效 HTTP 响应。在 HTTP header 末尾的终止 \r\n\r\n
之后,之后的所有内容都是消息正文数据。因此,您正在发送 \r\nHere is response data
作为图像的前几个字节,从而破坏了它们。您需要完全删除它,即使对于您的 txt
和 html
文件也是如此。
更糟糕的是,您在每次循环迭代 时发送msg
,因此您在每个文件数据缓冲区之前加上您的HTTP 响应字符串,进一步彻底破坏您的图像数据。
此外,您的响应缺少 Content-Length
和 Connection: close
响应 header 。
尝试更像这样的东西:
int sendRaw(int fd, const void *buf, int buflen)
{
const char *pbuf = static_cast<const char*>(buf);
int bytes_written;
while (buflen > 0) {
bytes_written = write(fd, pbuf, buflen);
if (written == -1) return -1;
pbuf += bytes_written;
buflen -= bytes_written;
}
return 0;
}
int sendStr(int fd, const string &s)
{
return sendRaw(fd, s.c_str(), s.length());
}
...
struct stat s;
fstat(in, &s);
off_t fileLength = s.st_size;
char buf[BUFSIZE];
int bytes_read, bytes_written;
if ((vrsn == "1.1") || (vrsn == "1.0")) {
ostringstream msg;
msg << "HTTP/1.0 200 OK\r\n"
<< "Content-Type:" << fileExt << "\r\n"
<< "Content-Length: " << fileLength << "\r\n"
<< "Connection: close\r\n"
<< "\r\n";
sendStr(fd, msg.str());
}
while (fileLength > 0) {
bytes_read = read(in, buf, min(fileLength, BUFSIZE));
if (bytes_read <= 0) break;
if (sendRaw(fd, buf, bytes_read) == -1) break;
fileLength -= bytes_read;
}
close(fd);
关于c++ - 在 C++ 中通过套接字发送图像时出现 "The image cannot be displayed error",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42516686/
我是一名优秀的程序员,十分优秀!