1'use strict'; 2require('../common'); 3const assert = require('assert'); 4 5const net = require('net'); 6 7// Sets the server's maxConnections property to 1. 8// Open 2 connections (connection 0 and connection 1). 9// Connection 0 should be accepted. 10// Connection 1 should be rejected. 11// Closes connection 0. 12// Open 2 more connections (connection 2 and 3). 13// Connection 2 should be accepted. 14// Connection 3 should be rejected. 15 16const connections = []; 17const received = []; 18const sent = []; 19 20function createConnection(index) { 21 console.error(`creating connection ${index}`); 22 23 return new Promise(function(resolve, reject) { 24 const connection = net.createConnection(server.address().port, function() { 25 const msg = String(index); 26 console.error(`sending message: ${msg}`); 27 this.write(msg); 28 sent.push(msg); 29 }); 30 31 connection.on('error', function(err) { 32 assert.strictEqual(err.code, 'ECONNRESET'); 33 resolve(); 34 }); 35 36 connection.on('data', function(e) { 37 console.error(`connection ${index} received response`); 38 resolve(); 39 }); 40 41 connection.on('end', function() { 42 console.error(`ending ${index}`); 43 resolve(); 44 }); 45 46 connections[index] = connection; 47 }); 48} 49 50function closeConnection(index) { 51 console.error(`closing connection ${index}`); 52 return new Promise(function(resolve, reject) { 53 connections[index].on('end', function() { 54 resolve(); 55 }); 56 connections[index].end(); 57 }); 58} 59 60const server = net.createServer(function(socket) { 61 socket.on('data', function(data) { 62 console.error(`received message: ${data}`); 63 received.push(String(data)); 64 socket.write('acknowledged'); 65 }); 66}); 67 68server.maxConnections = 1; 69 70server.listen(0, function() { 71 createConnection(0) 72 .then(createConnection.bind(null, 1)) 73 .then(closeConnection.bind(null, 0)) 74 .then(createConnection.bind(null, 2)) 75 .then(createConnection.bind(null, 3)) 76 .then(server.close.bind(server)) 77 .then(closeConnection.bind(null, 2)); 78}); 79 80process.on('exit', function() { 81 // Confirm that all connections tried to send data... 82 assert.deepStrictEqual(sent, ['0', '1', '2', '3']); 83 // ...but that only connections 0 and 2 were successful. 84 assert.deepStrictEqual(received, ['0', '2']); 85}); 86