3

我正在尝试使用服务器发送的事件将数据“流式传输”到 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,这就是显示返回值和执行时间的原因)

当我将 while() 循环放在 try{ }catch(...){} 之间时的事件,程序仍然在没有进入 catch 的情况下崩溃(当我将整个 main() 的内容放在 try/catch 之间时也会发生同样的事情)

主程序仅包含以下指令:

int main(int argc, char* argv[])
{
    MyServerApp myServer;
    myServer.run(argc, argv);

    return 0;
}

我想知道什么可能导致崩溃以及如何解决它,拜托。

预先感谢您的帮助 :)

4

2 回答 2

2

For anyone interested, I was able to deal with this issue by registering my own error handler that simply ignores the exception thrown when an SSE-client disconnects:

#include <Poco\ErrorHandler.h>

// Other includes, using namespace..., etc.

class ServerErrorHandler : public ErrorHandler
{
public:
    void exception(const Exception& e)
    {
        // Ignore an exception that's thrown when an SSE connection is closed. 
        //
        // Info: When the server is handling an SSE request, it keeps a persistent connection through a forever loop.
        //       In order to handle when a client disconnects, the request handler must detect such an event. Alas, this
        //       is not possible with the current request handler in Poco (we only have 2 params: request and response).
        //       The only hack for now is to simply ignore the exception generated when the client disconnects :(
        //
        if (string(e.className()).find("ConnectionAbortedException") == string::npos)
            poco_debugger_msg(e.what());
    }
};

class ServerApp : public ServerApplication 
{
protected:
    int main(const vector<string>& args) 
    {
        // Create and register our error handler
        ServerErrorHandler error_handler;
        ErrorHandler::set(&error_handler);

        // Normal server code, for example:
        HTTPServer server(new RequestHandlerFactory, 80, new HTTPServerParams);
        server.start();

        waitForTerminationRequest();
        server.stop();

        return Application::EXIT_OK;
    }
};


POCO_SERVER_MAIN(ServerApp);

However, I must say that this is an ugly hack. Moreover, the error handler is global to the application which makes it even less desirable as a solution. The correct way would be detect the disconnection and handle it. For that Poco must pass the SocketStream to the request handler.

于 2015-07-20T17:09:49.750 回答
0

您可以更改代码以捕获 Poco 异常:

try {
    MyServerApp myServer;
    return myServer.run(argc, argv);        
}catch(const Poco::Exception& ex) {
    std::cout << ex.displayText() << std::endl;
    return Poco::Util::Application::EXIT_SOFTWARE;
}
于 2014-01-24T17:32:22.370 回答