1 | var http = require('http');
|
2 | var net = require('net');
|
3 | var should = require('should');
|
4 | var tunnel = require('../index');
|
5 |
|
6 | describe('HTTP over HTTP', function() {
|
7 | it('should finish without error', function(done) {
|
8 | var serverPort = 3000;
|
9 | var proxyPort = 3001;
|
10 | var poolSize = 3;
|
11 | var N = 10;
|
12 | var serverConnect = 0;
|
13 | var proxyConnect = 0;
|
14 | var clientConnect = 0;
|
15 | var agent;
|
16 |
|
17 | var server = http.createServer(function(req, res) {
|
18 | ++serverConnect;
|
19 | res.writeHead(200);
|
20 | res.end('Hello' + req.url);
|
21 | });
|
22 | server.listen(serverPort, function() {
|
23 | var proxy = http.createServer(function(req, res) {
|
24 | should.fail();
|
25 | });
|
26 | proxy.on('connect', function(req, clientSocket, head) {
|
27 | req.method.should.equal('CONNECT');
|
28 | req.url.should.equal('localhost:' + serverPort);
|
29 | req.headers.should.have.property('proxy-authorization',
|
30 | 'Basic ' + new Buffer('user:password').toString('base64'));
|
31 | ++proxyConnect;
|
32 |
|
33 | var serverSocket = net.connect(serverPort, function() {
|
34 | clientSocket.write('HTTP/1.1 200 Connection established\r\n\r\n');
|
35 | clientSocket.pipe(serverSocket);
|
36 | serverSocket.write(head);
|
37 | serverSocket.pipe(clientSocket);
|
38 |
|
39 | serverSocket.on('end', function() {
|
40 | clientSocket.end();
|
41 | });
|
42 | });
|
43 | });
|
44 | proxy.listen(proxyPort, function() {
|
45 | agent = tunnel.httpOverHttp({
|
46 | maxSockets: poolSize,
|
47 | proxy: {
|
48 | port: proxyPort,
|
49 | proxyAuth: 'user:password'
|
50 | }
|
51 | });
|
52 |
|
53 | for (var i = 0; i < N; ++i) {
|
54 | (function(i) {
|
55 | var req = http.get({
|
56 | port: serverPort,
|
57 | path: '/' + i,
|
58 | agent: agent
|
59 | }, function(res) {
|
60 | res.setEncoding('utf8');
|
61 | res.on('data', function(data) {
|
62 | data.should.equal('Hello/' + i);
|
63 | });
|
64 | res.on('end', function() {
|
65 | ++clientConnect;
|
66 | if (clientConnect === N) {
|
67 | proxy.close();
|
68 | server.close();
|
69 | }
|
70 | });
|
71 | });
|
72 | })(i);
|
73 | }
|
74 | });
|
75 | });
|
76 |
|
77 | server.on('close', function() {
|
78 | serverConnect.should.equal(N);
|
79 | proxyConnect.should.equal(poolSize);
|
80 | clientConnect.should.equal(N);
|
81 |
|
82 | agent.sockets.should.have.lengthOf(0);
|
83 | agent.requests.should.have.lengthOf(0);
|
84 |
|
85 | done();
|
86 | });
|
87 | });
|
88 | });
|