summaryrefslogtreecommitdiff
path: root/test/simple/test-http-upgrade-client2.js
blob: bdd585a13cec3553b90ce7edf84e70c82b497ef8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
var common = require('../common');
var assert = require('assert');
var http = require('http');

var CRLF = '\r\n';

var server = http.createServer();
server.on('upgrade', function(req, socket, head) {
  socket.write('HTTP/1.1 101 Ok' + CRLF +
               'Connection: Upgrade' + CRLF +
               'Upgrade: Test' + CRLF + CRLF + 'head');
  socket.on('end', function() {
    socket.end();
  });
});

var successCount = 0;

server.listen(common.PORT, function() {

  var client = http.createClient(common.PORT);

  function upgradeRequest(fn) {
    console.log("req");
    var header = { 'Connection': 'Upgrade', 'Upgrade': 'Test' };
    var request = client.request('GET', '/', header);
    var wasUpgrade = false;

    function onUpgrade(res, socket, head) {
      console.log("client upgraded");
      wasUpgrade = true;

      client.removeListener('upgrade', onUpgrade);
      socket.end();
    }
    client.on('upgrade', onUpgrade);

    function onEnd() {
      console.log("client end");
      client.removeListener('end', onEnd);
      if (!wasUpgrade) {
        throw new Error('hasn\'t received upgrade event');
      } else {
        fn && process.nextTick(fn);
      }
    }
    client.on('end', onEnd);

    request.write('head');

  }

  upgradeRequest(function() {
    successCount++;
    upgradeRequest(function() {
      successCount++;
      // Test pass
      console.log('Pass!');
      client.end();
      client.destroy();
      server.close();
    });
  });

});

process.on('exit', function() {
  assert.equal(2, successCount);
});