如何检测用户取消请求

问题描述:

我正在通过编写一个非常基本的http / web缓存代理来尝试Node.js,并且遇到了一些我无法突破的事情。

I'm trying out Node.js by writing a very basic http/web caching proxy, and have hit something I haven't managed to break through.

假设我有一个非常基本的代理功能(监听请求,将其传递给外部服务器,等待响应,将其传回客户端),如何检测客户端(Web浏览器)何时取消请求?当用户在浏览器上单击停止/ Esc时,浏览器不会向我发送任何请求或信息,并且在响应连接结束时不会调用回调。

Assuming I have a very basic proxy functionality (listen to request, pipe it to external server, wait for response, pipe it back to client), how do I detect when the client (web browser) cancels the request? When the user clicks "Stop"/Esc on his browser, the browser doesn't send me any "request" or info and attaching a callback for when the "response" connection ends doesn't get called.

这就是我的意思:

http.createServer (clientRequest, clientResponse) {  
    var client = http.createClient (port, hostname);
    var request = client.request (method, url, headers);  

    request.addListener ('response', function(response){  
        response.addListener ('data', function(chunk){  
           // forward data to clientResponse..
        }  
        response.addListener ('end', function(){   
           // end clientResponse..  
        }  
    });  
    clientResponse.addListener('end', function(){  
        // this never gets called :(
        // I want it to terminate the request/response created just above  
    }
}


原来我应该绑定到关闭事件而不是请求的结束事件。
这实际上是有意义的。

我在这里发布这个可能遇到同样问题的其他人:

Turns out I should be binding to the "close" event instead of the "end" event of the request. That does actually make sense.
I'm posting this here for anyone else who might encounter the same issue:

clientResponse.addListener('close', function(){  
    // this gets called when the user terminates his request  
}