1'use strict'; 2const { Duplex } = require('stream'); 3const assert = require('assert'); 4 5const kCallback = Symbol('Callback'); 6const kOtherSide = Symbol('Other'); 7 8class DuplexSocket extends Duplex { 9 constructor() { 10 super(); 11 this[kCallback] = null; 12 this[kOtherSide] = null; 13 } 14 15 _read() { 16 const callback = this[kCallback]; 17 if (callback) { 18 this[kCallback] = null; 19 callback(); 20 } 21 } 22 23 _write(chunk, encoding, callback) { 24 assert.notStrictEqual(this[kOtherSide], null); 25 assert.strictEqual(this[kOtherSide][kCallback], null); 26 if (chunk.length === 0) { 27 process.nextTick(callback); 28 } else { 29 this[kOtherSide].push(chunk); 30 this[kOtherSide][kCallback] = callback; 31 } 32 } 33 34 _final(callback) { 35 this[kOtherSide].on('end', callback); 36 this[kOtherSide].push(null); 37 } 38} 39 40function makeDuplexPair() { 41 const clientSide = new DuplexSocket(); 42 const serverSide = new DuplexSocket(); 43 clientSide[kOtherSide] = serverSide; 44 serverSide[kOtherSide] = clientSide; 45 return { clientSide, serverSide }; 46} 47 48module.exports = makeDuplexPair; 49