Can a http server detect that a client has cancelled their request?

一个人想着一个人 提交于 2019-11-27 21:07:59

While @Oded is correct that HTTP is stateless between requests, app servers can indeed detect when the underlying TCP/IP connection has broken for the request being processed. Why is this? Because TCP is a stateful protocol for reliable connections.

A common technique for .Net web apps processing a resource intensive request is to check Response.IsClientConnected (docs) before starting the resource intensive work. There is no point in wasting CPU cycles to send an expensive response to a client that isn't there anymore.

private void Page_Load(object sender, EventArgs e)
{
    // Check whether the browser remains
    // connected to the server.
    if (Response.IsClientConnected)
    {
        // If still connected, do work
        DoWork();
    }
    else
    {
        // If the browser is not connected
        // stop all response processing.
        Response.End();
    }
}

Please reply with your target app server stack so I can provide a more relevant example.

Regarding your 2nd alternative to use XHR to post client page unload events to the server, @Oded's comment about HTTP being stateless between requests is spot on. This is unlikely to work, especially in a farm with multiple servers.

Oded

HTTP is stateless, hence the only way to detect a disconnected client is via timeouts.

See the answers to this SO question (Java Servlet : How to detect browser closing ?).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!