说明:
调用nodeJs API, http.createServer()返回的Server对象,有一个setTimeout()方法,可以传入你想要的连接时长,默认是1200000(即2分钟),改成0表示不会timeout。而response对象,也有一个setTimeout()方法,我不知道两者有什么区别,但是我的理解是server.setTimeout()是全局的,response.setTimeout()只针对本次request。
代码:
对于expressJs,相关代码是:
var server = http.createServer(app)
server.setTimeout(0)
server.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'))
})
对于restify,相关代码是:
server.server.setTimeout(0)
server.listen(8080, function () {
console.log('%s listening at %s', server.name, server.url)
})
var os = require('os')var http = require('http')
var fs = require('fs')
var server = http.createServer(function(req, res) {
if (/^\/a.html/.test(req.url)) {
fs.createReadStream('a.html').pipe(res)
} else {
console.log(req.connection.remoteAddress + ':' + req.connection.remotePort)
res.writeHead(200, {'Content-Type': 'text/plain'})
res.end('Hello World\n')
}
}).listen(8124)
server.setTimeout(0) //设置不超时,所以服务端不会主动关闭连接
console.log('start ' + os.hostname() + ':8124')