我发生了一个非常奇怪的错误。 我在Mac OS X Sierra上运行Node.js版本8.0.0。
我创建了一个非常简单的http服务器,在本例中8秒后基本上会向任何请求返回'ok'。
然后我使用'request'包每隔9秒向我的http服务器发出一个请求,并使用参数'forever'来保持http会话的活动。
两个中的一个请求完全正常,而另外一个请求返回“socket hang up”错误。
以下是重现此问题的非常简单的代码:
const http = require('http');
const request = require('request');
const port = 3000;
const server = http.createServer((req, res) => {
console.log('request');
setTimeout(() => {
res.end('ok');
}, 8000);
});
server.listen(port);
setInterval(() => {
request(`http://localhost:${port}/`, {forever: true}, (error, response, body) => {
if (error) return console.log('error', error);
console.log('done', body);
});
}, 9000);
当我运行此代码时,我在Macbook Pro上获得以下输出:
request
done ok
request
error { Error: socket hang up
at createHangUpError (_http_client.js:343:15)
at Socket.socketOnEnd (_http_client.js:435:23)
at emitNone (events.js:110:20)
at Socket.emit (events.js:207:7)
at endReadableNT (_stream_readable.js:1045:12)
at _combinedTickCallback (internal/process/next_tick.js:102:11)
at process._tickCallback (internal/process/next_tick.js:161:9) code: 'ECONNRESET' }
request
done ok
request
error { Error: socket hang up
at createHangUpError (_http_client.js:343:15)
at Socket.socketOnEnd (_http_client.js:435:23)
at emitNone (events.js:110:20)
at Socket.emit (events.js:207:7)
at endReadableNT (_stream_readable.js:1045:12)
at _combinedTickCallback (internal/process/next_tick.js:102:11)
at process._tickCallback (internal/process/next_tick.js:161:9) code: 'ECONNRESET' }
request
done ok
request
error { Error: socket hang up
at createHangUpError (_http_client.js:343:15)
at Socket.socketOnEnd (_http_client.js:435:23)
at emitNone (events.js:110:20)
at Socket.emit (events.js:207:7)
at endReadableNT (_stream_readable.js:1045:12)
at _combinedTickCallback (internal/process/next_tick.js:102:11)
at process._tickCallback (internal/process/next_tick.js:161:9) code: 'ECONNRESET' }
所以每次其他请求都会出现'socket hang up'错误。
似乎这个错误似乎没有出现在Ubuntu VPS上。
关于为什么会出现此问题的任何想法?