summaryrefslogtreecommitdiff
path: root/test/sequential/test-tcp-wrap-listen.js
blob: d16069f25dbeabeed3bd63b079c48f6d4ded4c2d (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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
'use strict';
var common = require('../common');
var assert = require('assert');

var TCP = process.binding('tcp_wrap').TCP;
var WriteWrap = process.binding('stream_wrap').WriteWrap;

var server = new TCP();

var r = server.bind('0.0.0.0', common.PORT);
assert.equal(0, r);

server.listen(128);

var sliceCount = 0, eofCount = 0;

var writeCount = 0;
var recvCount = 0;

server.onconnection = function(err, client) {
  assert.equal(0, client.writeQueueSize);
  console.log('got connection');

  function maybeCloseClient() {
    if (client.pendingWrites.length == 0 && client.gotEOF) {
      console.log('close client');
      client.close();
    }
  }

  client.readStart();
  client.pendingWrites = [];
  client.onread = function(err, buffer) {
    if (buffer) {
      assert.ok(buffer.length > 0);

      assert.equal(0, client.writeQueueSize);

      var req = new WriteWrap();
      req.async = false;
      var err = client.writeBuffer(req, buffer);
      assert.equal(err, 0);
      client.pendingWrites.push(req);

      console.log('client.writeQueueSize: ' + client.writeQueueSize);
      // 11 bytes should flush
      assert.equal(0, client.writeQueueSize);

      if (req.async)
        req.oncomplete = done;
      else
        process.nextTick(done.bind(null, 0, client, req));

      function done(status, client_, req_) {
        assert.equal(req, client.pendingWrites.shift());

        // Check parameters.
        assert.equal(0, status);
        assert.equal(client, client_);
        assert.equal(req, req_);

        console.log('client.writeQueueSize: ' + client.writeQueueSize);
        assert.equal(0, client.writeQueueSize);

        writeCount++;
        console.log('write ' + writeCount);
        maybeCloseClient();
      }

      sliceCount++;
    } else {
      console.log('eof');
      client.gotEOF = true;
      server.close();
      eofCount++;
      maybeCloseClient();
    }
  };
};

var net = require('net');

var c = net.createConnection(common.PORT);
c.on('connect', function() {
  c.end('hello world');
});

c.setEncoding('utf8');
c.on('data', function(d) {
  assert.equal('hello world', d);
  recvCount++;
});

c.on('close', function() {
  console.error('client closed');
});

process.on('exit', function() {
  assert.equal(1, sliceCount);
  assert.equal(1, eofCount);
  assert.equal(1, writeCount);
  assert.equal(1, recvCount);
});