在node.js中检测客户端连接的关闭

kar*_*ter 14 node.js

我使用node.js进行长期连接.我想知道如何在客户端连接关闭时检测到(可能是当用户关闭选项卡时).如何为此指定回调?

kar*_*ter 11

回答我自己的问题 - 您可以通过执行以下操作来检测客户端连接的关闭:

http.createServer(function(request, response) {    
    request.connection.addListener('close', function () {
        // callback is fired when connection closed (e.g. closing the browser)
    });
}
Run Code Online (Sandbox Code Playgroud)