1'use strict'; 2 3const common = require('../common'); 4const assert = require('assert'); 5const dgram = require('dgram'); 6 7const client = dgram.createSocket('udp4'); 8 9const toSend = [Buffer.alloc(256, 'x'), 10 Buffer.alloc(256, 'y'), 11 Buffer.alloc(256, 'z'), 12 'hello']; 13 14const received = []; 15let totalBytesSent = 0; 16let totalBytesReceived = 0; 17const arrayBufferViewsCount = common.getArrayBufferViews( 18 Buffer.from('') 19).length; 20 21client.on('listening', common.mustCall(() => { 22 const port = client.address().port; 23 24 client.send(toSend[0], 0, toSend[0].length, port); 25 client.send(toSend[1], port); 26 client.send([toSend[2]], port); 27 client.send(toSend[3], 0, toSend[3].length, port); 28 29 totalBytesSent += toSend.map((buf) => buf.length) 30 .reduce((a, b) => a + b, 0); 31 32 for (const msgBuf of common.getArrayBufferViews(toSend[0])) { 33 client.send(msgBuf, 0, msgBuf.byteLength, port); 34 totalBytesSent += msgBuf.byteLength; 35 } 36 for (const msgBuf of common.getArrayBufferViews(toSend[1])) { 37 client.send(msgBuf, port); 38 totalBytesSent += msgBuf.byteLength; 39 } 40 for (const msgBuf of common.getArrayBufferViews(toSend[2])) { 41 client.send([msgBuf], port); 42 totalBytesSent += msgBuf.byteLength; 43 } 44})); 45 46client.on('message', common.mustCall((buf, info) => { 47 received.push(buf.toString()); 48 totalBytesReceived += info.size; 49 50 if (totalBytesReceived === totalBytesSent) { 51 client.close(); 52 } 53 // For every buffer in `toSend`, we send the raw Buffer, 54 // as well as every TypedArray in getArrayBufferViews() 55}, toSend.length + (toSend.length - 1) * arrayBufferViewsCount)); 56 57client.on('close', common.mustCall((buf, info) => { 58 // The replies may arrive out of order -> sort them before checking. 59 received.sort(); 60 61 const repeated = [...toSend]; 62 for (let i = 0; i < arrayBufferViewsCount; i++) { 63 repeated.push(...toSend.slice(0, 3)); 64 } 65 66 assert.strictEqual(totalBytesSent, totalBytesReceived); 67 68 const expected = repeated.map(String).sort(); 69 assert.deepStrictEqual(received, expected); 70})); 71 72client.bind(0); 73