我正在尝试使用服务器发送事件将数据“流式传输”到HTML5页面。这个http://www.html5rocks.com/en/tutorials/eventsource/basics/教程对于让客户端工作非常有帮助。但是对于服务器端,我正在做类似于http://pocoproject.org/slides/200-Network.pdf中HTTPServer示例的事情。html5rocks.com教程为请求处理程序的代码提供了以下思路:
void MyRequestHandler::handleRequest (HTTPServerRequest &req, HTTPServerResponse &resp)
{
resp.setStatus(HTTPResponse::HTTP_OK);
resp.add("Content-Type", "text/event-stream");
resp.add("Cache-Control", "no-cache");
ostream& out = resp.send();
while (out.good())
{
out << "data: " << "some data" << "\n\n";
out.flush();
Poco::Thread::sleep(500)
}
}
和HTML5页面的源代码:
<!DOCTYPE html>
<html>
<head>
<title>HTLM5Application</title>
</head>
<body>
<p id="demo">hello</p>
<script>
var msgCounter = 0;
var source;
var data;
if(typeof(EventSource) !== "undefined")
{
source = new EventSource('/stream');
document.getElementById("demo").innerHTML = "Event source created";
}
else
{
document.getElementById("demo").innerHTML = "Are you using IE ?";
}
source.addEventListener('message', function(e)
{
msgCounter++;
document.getElementById("demo").innerHTML = "Message received (" + msgCounter + ") !<br/>"+ e.data;
}, false);
</script>
</body>
</html>
好消息是,打开HTML页面时,数据会被流式传输,我可以得到正确的输出(在标签之间的文本按预期更新)。
问题是,当我关闭浏览器中的页面时,POCO程序会崩溃,并且我会在控制台中收到以下消息:
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
Process returned 3 (0x3) execution time : 22.234 s
Press any key to continue.
我正在使用Code::Blocks,因此返回值和执行时间会显示。
即使我在try{}catch(...){}之间放置while()循环,程序仍会崩溃,而没有进入catch(当我将整个main()的内容放置在try/catch之间时也是同样的情况)。
主程序仅包含这些指令:
int main(int argc, char* argv[])
{
MyServerApp myServer;
myServer.run(argc, argv);
return 0;
}
我想知道是什么原因导致了这个崩溃,以及如何修复它,请帮忙解答。
非常感谢您的帮助 :)