我需要在C ++服务器和有角度的客户端之间创建WebSocket
通信。我使用了POCO库和 websocket服务器示例。我设法在服务器和客户端之间交换数据。
我的问题是,当我更新网页(F5)时,服务器关闭。
我应该处理什么异常?
class WebSocketRequestHandler : public HTTPRequestHandler
/// Handle a WebSocket connection.
{
public:
void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
{
Application& app = Application::instance();
try
{
WebSocket ws(request, response);
app.logger().information("WebSocket connection established.");
char buffer[1024];
do
{
n = ws.receiveFrame(buffer, sizeof(buffer), flags);
cout << buffer << endl;
} while (n > 0 && (flags & WebSocket::FRAME_OP_BITMASK) != WebSocket::FRAME_OP_CLOSE);
app.logger().information("WebSocket connection closed.");
}
catch (WebSocketException& exc)
{
app.logger().log(exc);
switch (exc.code())
{
case WebSocket::WS_ERR_HANDSHAKE_UNSUPPORTED_VERSION:
response.set("Sec-WebSocket-Version", WebSocket::WEBSOCKET_VERSION);
case WebSocket::WS_ERR_NO_HANDSHAKE:
case WebSocket::WS_ERR_HANDSHAKE_NO_VERSION:
case WebSocket::WS_ERR_HANDSHAKE_NO_KEY:
response.setStatusAndReason(HTTPResponse::HTTP_BAD_REQUEST);
response.setContentLength(0);
response.send();
break;
}
}
}
};
答案 0 :(得分:0)
我也在应用程序中捕获了Poco::Exception
。它运作良好,没有崩溃:
catch (WebSocketException& exception)
{
switch (exception.code())
{
case WebSocket::WS_ERR_HANDSHAKE_UNSUPPORTED_VERSION:
response.set("Sec-WebSocket-Version", WebSocket::WEBSOCKET_VERSION);
// No break, fall through
case WebSocket::WS_ERR_NO_HANDSHAKE:
case WebSocket::WS_ERR_HANDSHAKE_NO_VERSION:
case WebSocket::WS_ERR_HANDSHAKE_NO_KEY:
response.setStatusAndReason(HTTPResponse::HTTP_BAD_REQUEST);
response.setContentLength(0);
response.send();
break;
}
}
catch (Poco::Exception& exception)
{
_logger.error("[%s] handle request {%s}", caller(), exception.displayText());
}