|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +require('../common'); |
| 4 | +const assert = require('assert'); |
| 5 | +const http = require('http'); |
| 6 | + |
| 7 | +class DestroyAgent extends http.Agent { |
| 8 | + constructor(options = {}) { |
| 9 | + // change all socket keepAlive by default |
| 10 | + options.keepAlive = true; |
| 11 | + super(options); |
| 12 | + |
| 13 | + this.requestCount = 0; |
| 14 | + this.destroyCount = 0; |
| 15 | + } |
| 16 | + |
| 17 | + init() { |
| 18 | + this.on('free', (socket, options) => { |
| 19 | + const name = this.getName(options); |
| 20 | + console.info('free socket %s', name); |
| 21 | + this.destroyCount++; |
| 22 | + socket.destroy(); |
| 23 | + }); |
| 24 | + } |
| 25 | + |
| 26 | + addRequest(req, options) { |
| 27 | + this.requestCount++; |
| 28 | + console.info('new request %s %s', req.method, req.path); |
| 29 | + return super.addRequest(req, options); |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +const server = http.Server(function(req, res) { |
| 34 | + res.writeHead(200); |
| 35 | + res.end('hello world\n'); |
| 36 | +}); |
| 37 | + |
| 38 | +server.listen(0, () => { |
| 39 | + const port = server.address().port; |
| 40 | + const destroyAgent = new DestroyAgent(); |
| 41 | + http.get({ port: port, path: '/', agent: destroyAgent }, (res) => { |
| 42 | + res.resume(); |
| 43 | + res.on('end', () => { |
| 44 | + http.get({ port: port, path: '/again', agent: destroyAgent }, (res) => { |
| 45 | + res.resume(); |
| 46 | + res.on('end', () => { |
| 47 | + // wait socket "close callbacks" phase execute |
| 48 | + setTimeout(() => { |
| 49 | + console.error('requestCount: %s, destroyCount: %s, closing server', |
| 50 | + destroyAgent.requestCount, destroyAgent.destroyCount); |
| 51 | + assert.strictEqual(destroyAgent.requestCount, 2); |
| 52 | + assert.strictEqual(destroyAgent.destroyCount, 2); |
| 53 | + server.close(); |
| 54 | + }, 100); |
| 55 | + }); |
| 56 | + }).on('error', function(e) { |
| 57 | + console.log('Error!', e); |
| 58 | + process.exit(1); |
| 59 | + }); |
| 60 | + }); |
| 61 | + }).on('error', function(e) { |
| 62 | + console.log('Error!', e); |
| 63 | + process.exit(1); |
| 64 | + }); |
| 65 | +}); |
0 commit comments