有是,隨着HTTP響應.png文件服務器:的boost :: ASIO文件發送
#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;
}
}
每次發生錯誤:
例外:連接被對方復位
我可以在瀏覽器中看到圖像的某些部分,有時圖像幾乎完整,但不會出現錯誤。
如果我使用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
任何想法如何解決呢?
我已編輯源和問題。沒有什麼幫助( – spe 2012-03-07 08:22:12
我完全不知道是什麼原因導致了這種情況,但它可能與開始回覆之前不等待請求有關 您應該儘可能少地執行HTTP協議的行解析,並等待,直到你收到一個雙重換行序列 除此之外,我真的不能看到任何明顯的做錯了,除了不正確的行終止(HTTP期望\ r \ n),但我懷疑這是你的原因問題,我假定文件在傳輸過程中沒有改變,當然, – Rawler 2012-03-07 09:13:46
你很可能!你應該至少做一下HTTP協議的行解析,然後等到你收到一個double-newline-序列。 – spe 2012-03-07 09:34:21