我正在使用 uWebSockets C++ 尝试返回二进制缓冲区。当我这样做res->end(...)
时,它会发送并清空响应,这是我的代码:
.get("/binaryfile", [](auto *res, auto *req) {
const char * fname = "../server/test.png";
FILE* filp = fopen(fname, "rb" );
if(!filp) {
res->end("File not found!");
} else {
std::cout << "File found" << std::endl;
char * buffer = new char[BUFFERSIZE];
std::string result;
size_t bt = 0;
size_t total_size = 0;
while ( (bt = fread(buffer, sizeof(char), BUFFERSIZE, filp)) > 0 ) {
result.append(buffer);
total_size = total_size + bt;
}
// Done and close.
fclose(filp);
std::string_view bd(result.c_str(), total_size);
res->writeHeader("Content-Type", "image/png");
std::cout << bd <<std::endl;
res->end(bd);
}
当我使用 cURL 检查时,我得到了这个:
> GET /binaryfile HTTP/1.1
> Host: 192.168.0.104:3000
> User-Agent: curl/7.58.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: image/png
< uWebSockets: 18
< Content-Length: 3097
<
Warning: Binary output can mess up your terminal. Use "--output -" to tell
Warning: curl to output it to your terminal anyway, or consider "--output
Warning: <FILE>" to save to a file.
* Failed writing body (0 != 1365)
* stopped the pause stream!
* Closing connection 0
如您所见,就在没有问题res->end(bd)
的情况下std::cout << bd << std::endl;
,将内容写入其中stdout
。那么,为什么不将内容作为响应发送?