2013-01-02 30 views
2

在nodejs.org socket.setTimeout,它說如何發送效應初探時超時在node.js中的HTTP模塊

當空閒超時被觸發插座會收到一個「超時」的事件,但是連接將不會切斷。

但是當我測試這樣的代碼:

var http = require('http'); 

server = http.createServer(function (request, response) { 
    request.socket.setTimeout(500); 
    request.socket.on('timeout', function() { 
     response.writeHead(200, {'content-type': 'text/html'}); 
     response.end('hello world'); 
     console.log('timeout'); 
    }); 
}); 

server.listen(8080); 

套接字超時後立即關閉,並且沒有數據回覆到瀏覽器。這與文件完全不同。這是一個錯誤還是有任何處理http模塊下的套接字的技巧?

回答

5

該文檔確實是正確的,但它看起來像http模塊添加一個「超時」偵聽器,它調用socket.destroy()。所以你需要做的是通過調用request.socket.removeAllListeners('timeout')來擺脫那個聆聽者。 所以你的代碼看起來應該是這樣的:

var http = require('http'); 

server = http.createServer(function (request, response) { 
    request.socket.setTimeout(500); 
    request.socket.removeAllListeners('timeout'); 
    request.socket.on('timeout', function() { 
     response.writeHead(200, {'content-type': 'text/html'}); 
     response.end('hello world'); 
     console.log('timeout'); 
    }); 
}); 

server.listen(8080); 
+0

我已經測試了你的代碼,它運行的很完美,thx非常多。 – Jack

相關問題