gpt4 book ai didi

c++ - boost::asio 文件发送

转载 作者:搜寻专家 更新时间:2023-10-31 01:15:54 25 4
gpt4 key购买 nike

有一个服务器通过 http 响应 .png 文件:

#include "server.h"
string Server::header(int contentLength)
{
string h =
"HTTP/1.1 200 OK\n"
"Content-Length: " + boost::lexical_cast<string>(contentLength) + "\n"
"Content-Type: image/png;\n"
"Connection: close\n"
"\n";
return h;
}
string Server::readMap(const string &filename)
{
ifstream file (filename.c_str(), ios::in|ios::binary);
string reply;
char buf[512];
while (file.read(buf, sizeof(buf)).gcount() > 0)
reply.append(buf, file.gcount());
return reply;
}
void Server::run(const string &filename, int port)
{
string data = readMap(filename);
try
{
boost::asio::io_service io_service;
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), port));
for (;;)
{
tcp::socket socket(io_service);
acceptor.accept(socket);
boost::asio::write(socket, boost::asio::buffer(header( data.size() )));
boost::asio::write(socket, boost::asio::buffer(data));
}
}
catch (std::exception& e)
{
cerr << "exception: " << e.what() << endl;
}
}

每次发生错误时:

exception: Connection reset by peer

我可以在我的浏览器中看到图像的某些部分,有时图像几乎是完整的,但它永远不会在没有错误的情况下工作。

如果我使用 wget 看起来像

wget http://localhost:8089
--2012-03-07 12:07:19-- http://localhost:8089/
Resolving localhost... 127.0.0.1
Connecting to localhost|127.0.0.1|:8089... connected.
HTTP request sent, awaiting response... 200 OK
Length: 760032 (742K) [image/png]
Saving to: `index.html'

62% [========================================================> ] 475,136 --.-K/s in 0.002s

2012-03-07 12:07:19 (287 MB/s) - Read error at byte 475136/760032 (Connection reset by peer). Retrying.

--2012-03-07 12:07:20-- (try: 2) http://localhost:8089/
Connecting to localhost|127.0.0.1|:8089... connected.
HTTP request sent, awaiting response... 200 OK
Length: 760032 (742K) [image/png]
Saving to: `index.html'

73% [==================================================================> ] 557,056 --.-K/s in 0.001s

... many failes and finally

--2012-03-07 12:09:01-- (try: 9) http://localhost:8089/
Connecting to localhost|127.0.0.1|:8089... connected.
HTTP request sent, awaiting response... 200 OK
Length: 760032 (742K) [image/png]
Saving to: `index.html'

100%[===========================================================================================>] 760,032 --.-K/s in 0.001s

有什么解决办法吗?

最佳答案

ASIO 文档中有几个更完整的 HTTP 实现,包括静态文件服务。一种方法是为您的应用程序重用部分示例代码。

在这种特殊情况下,在 http://www.boost.org/doc/libs/1_49_0/doc/html/boost_asio/example/http/server/request_handler.cpp 处有一个如何正确打开和缓冲文件的示例

  std::ifstream is(full_path.c_str(), std::ios::in | std::ios::binary);
...
char buf[512];
while (is.read(buf, sizeof(buf)).gcount() > 0)
rep.content.append(buf, is.gcount());

该文档还有实际异步 HTTP 实现的示例。 (我假设您正在使用 boost::asio 最终使其异步?)

关于c++ - boost::asio 文件发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9587777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com