This repository has been archived by the owner on Jan 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdgram.js
1157 lines (958 loc) · 29.2 KB
/
dgram.js
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @module Dgram
*
* This module provides an implementation of UDP datagram sockets. It does
* not (yet) provide any of the multicast methods or properties.
*/
import { isArrayBufferView, isFunction, rand64, noop } from './util.js'
import { InternalError } from './errors.js'
import { EventEmitter } from './events.js'
import { Buffer } from './buffer.js'
import { isIPv4 } from './net.js'
import * as ipc from './ipc.js'
import console from './console.js'
import dns from './dns.js'
import gc from './gc.js'
import * as exports from './dgram.js'
const BIND_STATE_UNBOUND = 0
const BIND_STATE_BINDING = 1
const BIND_STATE_BOUND = 2
const CONNECT_STATE_DISCONNECTED = 0
const CONNECT_STATE_CONNECTING = 1
const CONNECT_STATE_CONNECTED = 2
const MAX_PORT = 64 * 1024
const RECV_BUFFER = 1
const SEND_BUFFER = 0
/**
* Generic error class for an error occurring on a `Socket` instance.
* @ignore
*/
export class SocketError extends InternalError {
get code () { return this.constructor.name }
}
/**
* Thrown when a socket is already bound.
*/
export class ERR_SOCKET_ALREADY_BOUND extends SocketError {
get message () { return 'Socket is already bound' }
}
/**
* @ignore
*/
export class ERR_SOCKET_BAD_BUFFER_SIZE extends SocketError {}
/**
* @ignore
*/
export class ERR_SOCKET_BUFFER_SIZE extends SocketError {}
/**
* Thrown when the socket is already connected.
*/
export class ERR_SOCKET_DGRAM_IS_CONNECTED extends SocketError {
get message () { return 'Alread connected' }
}
/**
* Thrown when the socket is not connected.
*/
export class ERR_SOCKET_DGRAM_NOT_CONNECTED extends SocketError {
syscall = 'getpeername'
get message () { return 'Not connected' }
}
/**
* Thrown when the socket is not running (not bound or connected).
*/
export class ERR_SOCKET_DGRAM_NOT_RUNNING extends SocketError {
get message () { return 'Not running' }
}
/**
* Thrown when a bad socket type is used in an argument.
*/
export class ERR_SOCKET_BAD_TYPE extends TypeError {
code = 'ERR_SOCKET_BAD_TYPE'
get message () {
return 'Bad socket type specified. Valid types are: udp4, udp6'
}
}
/**
* Thrown when a bad port is given.
*/
export class ERR_SOCKET_BAD_PORT extends RangeError {
code = 'ERR_SOCKET_BAD_PORT'
}
function defaultCallback (socket) {
return (err) => {
if (err) socket.emit('error', err)
}
}
function createDataListener (socket) {
// subscribe this socket to the firehose
window.addEventListener('data', ondata)
return ondata
function ondata ({ detail }) {
const { err, data, source } = detail.params
const buffer = detail.data
if (err && err.id === socket.id) {
return socket.emit('error', err)
}
if (!data || BigInt(data.id) !== socket.id) return
if (source === 'udp.readStart') {
const info = {
...data,
family: getAddressFamily(data.address)
}
socket.emit('message', Buffer.from(buffer), info)
}
if (data.EOF) {
window.removeEventListener('data', ondata)
}
}
}
function destroyDataListener (socket) {
if (typeof socket?.dataListener === 'function') {
window.removeEventListener('data', socket.dataListener)
delete socket.dataListener
}
}
function fromBufferList (list) {
const newlist = new Array(list.length)
for (let i = 0, l = list.length; i < l; i++) {
const buf = list[i]
if (typeof buf === 'string') {
newlist[i] = Buffer.from(buf)
} else if (!isArrayBufferView(buf)) {
return null
} else {
newlist[i] = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
}
}
return newlist
}
function getDefaultAddress (socket, local) {
if (local) {
if (socket.type === 'udp4') return '127.0.0.1'
if (socket.type === 'udp6') return '::1'
} else {
if (socket.type === 'udp4') return '0.0.0.0'
if (socket.type === 'udp6') return '::'
}
return null
}
function getAddressFamily (address) {
return isIPv4(address) ? 'IPv4' : 'IPv6'
}
function getSocketState (socket) {
const result = ipc.sendSync('udp.getState', { id: socket.id })
if (result.err && result.err.code !== 'NOT_FOUND_ERR') {
throw result.err
}
return result.data || null
}
// eslint-disable-next-line no-unused-vars
function healhCheck (socket) {
// @TODO(jwerle)
}
async function startReading (socket, callback) {
let result = null
if (!isFunction(callback)) {
callback = noop
}
try {
result = await ipc.send('udp.readStart', {
id: socket.id
})
callback(result.err, result.data)
} catch (err) {
callback(err)
}
return result
}
async function stopReading (socket, callback) {
let result = null
if (!isFunction(callback)) {
callback = noop
}
try {
result = await ipc.send('udp.readStop', {
id: socket.id
})
callback(result.err, result.data)
} catch (err) {
callback(err)
}
return result
}
async function getRecvBufferSize (socket, callback) {
let result = null
if (!isFunction(callback)) {
callback = noop
}
try {
result = await ipc.send('os.bufferSize', {
id: socket.id,
buffer: RECV_BUFFER
})
callback(result.err, result.data)
} catch (err) {
callback(err)
return { err }
}
return result
}
async function getSendBufferSize (socket, callback) {
let result = null
if (!isFunction(callback)) {
callback = noop
}
try {
result = await ipc.send('os.bufferSize', {
id: socket.id,
buffer: SEND_BUFFER
})
callback(result.err, result.data)
} catch (err) {
callback(err)
return { err }
}
return result
}
async function bind (socket, options, callback) {
let result = null
options = { ...options }
if (!isFunction(callback)) {
callback = noop
}
if (typeof options.address !== 'string') {
options.address = getDefaultAddress(socket)
}
socket.state.bindState = BIND_STATE_BINDING
if (typeof options.address === 'string' && !isIPv4(options.address)) {
try {
options.address = await dns.lookup(options.address, 4)
} catch (err) {
socket.state.bindState = BIND_STATE_UNBOUND
callback(err)
return { err }
}
}
try {
result = await ipc.send('udp.bind', {
id: socket.id,
port: options.port || 0,
address: options.address,
ipv6Only: !!options.ipv6Only,
reuseAddr: !!options.reuseAddr
})
socket.state.bindState = BIND_STATE_BOUND
if (socket.state.sendBufferSize) {
await socket.setSendBufferSize(socket.state.sendBufferSize)
} else {
const result = await getSendBufferSize(socket)
if (result.err) {
callback(result.err)
return { err: result.err }
}
socket.state.sendBufferSize = result.data.size
}
if (socket.state.recvBufferSize) {
await socket.setRecvBufferSize(socket.state.recvBufferSize)
} else {
const result = await getRecvBufferSize(socket)
if (result.err) {
callback(result.err)
return { err: result.err }
}
socket.state.recvBufferSize = result.data.size
}
callback(result.err, result.data)
} catch (err) {
socket.state.bindState = BIND_STATE_UNBOUND
callback(err)
return { err }
}
return result
}
async function connect (socket, options, callback) {
let result = null
options = { ...options }
if (!isFunction(callback)) {
callback = noop
}
if (typeof options.address !== 'string') {
options.address = getDefaultAddress(socket)
}
socket.state.connectState = CONNECT_STATE_CONNECTING
if (typeof options.address === 'string' && !isIPv4(options.address)) {
try {
options.address = await dns.lookup(options.address, 4)
} catch (err) {
socket.state.connectState = CONNECT_STATE_DISCONNECTED
callback(err)
return { err }
}
}
const { err } = await bind(socket, { port: 0 })
if (err) {
socket.state.connectState = CONNECT_STATE_DISCONNECTED
callback(err)
return { err }
}
try {
result = await ipc.send('udp.connect', {
id: socket.id,
port: options?.port ?? 0,
address: options?.address
})
socket.state.connectState = CONNECT_STATE_CONNECTED
if (socket.state.sendBufferSize) {
await socket.setSendBufferSize(socket.state.sendBufferSize)
} else {
const result = await getSendBufferSize(socket)
if (result.err) {
callback(result.err)
return { err }
}
socket.state.sendBufferSize = result.data.size
}
if (socket.state.recvBufferSize) {
await socket.setRecvBufferSize(socket.state.recvBufferSize)
} else {
const result = await getRecvBufferSize(socket)
if (result.err) {
callback(result.err)
return { err }
}
socket.state.recvBufferSize = result.data.size
}
callback(result.err, result.data)
} catch (err) {
socket.state.connectState = CONNECT_STATE_DISCONNECTED
callback(err)
return { err }
}
return result
}
function disconnect (socket, callback) {
let result = null
if (!isFunction(callback)) {
callback = noop
}
try {
result = ipc.sendSync('udp.disconnect', {
id: socket.id
})
delete socket.state.remoteAddress
socket.state.connectState = CONNECT_STATE_DISCONNECTED
callback(result.err, result.data)
} catch (err) {
callback(err)
return { err }
}
return result
}
async function send (socket, options, callback) {
let result = null
if (!isFunction(callback)) {
callback = noop
}
options = { ...options }
if (socket.state.connectState === CONNECT_STATE_DISCONNECTED) {
// wait for bind to finish
if (socket.state.bindState === BIND_STATE_BINDING) {
const { err } = await new Promise((resolve, reject) => {
socket.once('listening', () => resolve({}))
socket.once('error', (err) => resolve({ err }))
})
if (err) {
callback(err)
return { err }
}
} else if (socket.state.bindState === BIND_STATE_UNBOUND) {
const { err } = await bind(socket, { port: 0 })
if (err) {
callback(err)
return { err }
}
}
}
// wait for connect to finish
if (socket.state.connectState === CONNECT_STATE_CONNECTING) {
const { err } = await new Promise((resolve, reject) => {
socket.once('connect', () => resolve({}))
socket.once('error', (err) => resolve({ err }))
})
if (err) {
callback(err)
return { err }
}
}
if (
!isIPv4(options.address) &&
typeof options.address === 'string' &&
socket.state.connectState !== CONNECT_STATE_CONNECTED
) {
try {
options.address = await dns.lookup(options.address, 4)
} catch (err) {
callback(err)
return { err }
}
}
// use local port/address if not given
if (socket.state.bindState === BIND_STATE_BOUND) {
const local = socket.address()
if (!options.address) {
options.address = local.address
}
if (!options.port) {
options.port = local.port
}
}
// use remote port/address if not given
if (socket.state.connectState === CONNECT_STATE_CONNECTED) {
const remote = socket.remoteAddress()
if (!options.address) {
options.address = remote.address
}
if (!options.port) {
options.port = remote.port
}
}
if (options.port && !options.address) {
options.address = getDefaultAddress(socket)
}
try {
result = await ipc.write('udp.send', {
id: socket.id,
port: options.port,
address: options.address
}, options.buffer)
callback(result.err, result.data)
} catch (err) {
callback(err)
return { err }
}
return result
}
async function close (socket, callback) {
let result = null
if (!isFunction(callback)) {
callback = noop
}
socket.state.connectState = CONNECT_STATE_DISCONNECTED
socket.state.bindState = BIND_STATE_UNBOUND
await stopReading(socket)
await disconnect(socket)
try {
result = await ipc.send('udp.close', {
id: socket.id
})
gc.unref(socket)
delete socket.state.address
delete socket.state.remoteAddress
callback(result.err, result.data)
} catch (err) {
callback(err)
return { err }
}
return result
}
function getPeerName (socket, callback) {
let result = null
if (!isFunction(callback)) {
callback = noop
}
try {
result = ipc.sendSync('udp.getPeerName', {
id: socket.id
})
callback(result.err, result.data)
} catch (err) {
callback(err)
return { err }
}
return result
}
function getSockName (socket, callback) {
let result = null
if (!isFunction(callback)) {
callback = noop
}
try {
result = ipc.sendSync('udp.getSockName', {
id: socket.id
})
callback(result.err, result.data)
} catch (err) {
callback(err)
return { err }
}
return result
}
/**
* @typedef {Object} SocketOptions
*/
/**
* Creates a `Socket` instance.
* @param {string|Object} options - either a string ('udp4' or 'udp6') or an options object
* @param {string=} options.type - The family of socket. Must be either 'udp4' or 'udp6'. Required.
* @param {boolean=} [options.reuseAddr=false] - When true socket.bind() will reuse the address, even if another process has already bound a socket on it. Default: false.
* @param {boolean=} [options.ipv6Only=false] - Setting ipv6Only to true will disable dual-stack support, i.e., binding to address :: won't make 0.0.0.0 be bound. Default: false.
if ()
* @param {number=} options.recvBufferSize - Sets the SO_RCVBUF socket value.
* @param {number=} options.sendBufferSize - Sets the SO_SNDBUF socket value.
* @param {AbortSignal=} options.signal - An AbortSignal that may be used to close a socket.
* @param {function=} callback - Attached as a listener for 'message' events. Optional.
* @return {Socket}
*/
export const createSocket = (options, callback) => new Socket(options, callback)
/**
* New instances of dgram.Socket are created using dgram.createSocket().
* The new keyword is not to be used to create dgram.Socket instances.
*/
export class Socket extends EventEmitter {
constructor (options, callback) {
super()
this.id = rand64()
if (typeof options === 'string') {
options = { type: options }
}
options = { ...options }
if (!['udp4', 'udp6'].includes(options.type)) {
throw new ERR_SOCKET_BAD_TYPE()
}
this.type = options.type
this.signal = options?.signal ?? null
this.state = {
recvBufferSize: options.recvBufferSize,
sendBufferSize: options.sendBufferSize,
bindState: BIND_STATE_UNBOUND,
connectState: CONNECT_STATE_DISCONNECTED,
reuseAddr: options.reuseAddr === true,
ipv6Only: options.ipv6Only === true
}
if (isFunction(callback)) {
this.on('message', callback)
}
const onabort = () => this.close()
this.signal?.addEventListener('abort', onabort, { once: true })
this.once('close', () => {
destroyDataListener(this)
this.removeAllListeners()
this.signal?.removeEventListener('abort', onabort)
})
gc.ref(this, options)
}
/**
* Implements `gc.finalizer` for gc'd resource cleanup.
* @return {gc.Finalizer}
* @ignore
*/
[gc.finalizer] (options) {
return {
args: [this.id, options],
async handle (id) {
console.warn('Closing Socket on garbage collection')
await ipc.send('udp.close', { id }, options)
}
}
}
/**
* Listen for datagram messages on a named port and optional address
* If address is not specified, the operating system will attempt to
* listen on all addresses. Once binding is complete, a 'listening'
* event is emitted and the optional callback function is called.
*
* If binding fails, an 'error' event is emitted.
*
* @param {number} port - The port to to listen for messages on
* @param {string} address - The address to bind to (0.0.0.0)
* @param {function} callback - With no parameters. Called when binding is complete.
* @see {@link https://nodejs.org/api/dgram.html#socketbindport-address-callback}
*/
bind (arg1, arg2, arg3) {
const options = {}
const cb = isFunction(arg2)
? arg2
: isFunction(arg3)
? arg3
: defaultCallback(this)
if (typeof arg1 === 'number' || typeof arg2 === 'string') {
options.port = parseInt(arg1)
} else if (typeof arg1 === 'object') {
Object.assign(options, arg1)
}
if (typeof arg2 === 'string') {
options.address = arg2
}
bind(this, options, (err, info) => {
if (err) {
return cb(err)
}
startReading(this, (err) => {
if (err) {
cb(err)
} else {
this.dataListener = createDataListener(this)
cb(null)
this.emit('listening')
}
})
})
return this
}
/**
* Associates the dgram.Socket to a remote address and port. Every message sent
* by this handle is automatically sent to that destination. Also, the socket
* will only receive messages from that remote peer. Trying to call connect()
* on an already connected socket will result in an ERR_SOCKET_DGRAM_IS_CONNECTED
* exception. If address is not provided, '127.0.0.1' (for udp4 sockets) or '::1'
* (for udp6 sockets) will be used by default. Once the connection is complete,
* a 'connect' event is emitted and the optional callback function is called.
* In case of failure, the callback is called or, failing this, an 'error' event
* is emitted.
*
* @param {number} port - Port the client should connect to.
* @param {string=} host - Host the client should connect to.
* @param {function=} connectListener - Common parameter of socket.connect() methods. Will be added as a listener for the 'connect' event once.
* @see {@link https://nodejs.org/api/dgram.html#socketconnectport-address-callback}
*/
connect (arg1, arg2, arg3) {
const address = isFunction(arg2) ? undefined : arg2
const port = parseInt(arg1)
const cb = isFunction(arg2)
? arg2
: isFunction(arg3)
? arg3
: defaultCallback(this)
if (!Number.isInteger(port) || port <= 0 || port > MAX_PORT) {
throw new ERR_SOCKET_BAD_PORT(
`Port should be > 0 and < 65536. Received ${arg1}.`
)
}
if (this.state.connectState !== CONNECT_STATE_DISCONNECTED) {
throw new ERR_SOCKET_DGRAM_IS_CONNECTED()
}
connect(this, { address, port }, (err, info) => {
cb(err, info)
if (!err && info) {
this.emit('connect', info)
}
})
}
/**
* A synchronous function that disassociates a connected dgram.Socket from
* its remote address. Trying to call disconnect() on an unbound or already
* disconnected socket will result in an ERR_SOCKET_DGRAM_NOT_CONNECTED exception.
*
* @see {@link https://nodejs.org/api/dgram.html#socketdisconnect}
*/
disconnect () {
if (this.state.connectState !== CONNECT_STATE_CONNECTED) {
throw new ERR_SOCKET_DGRAM_NOT_CONNECTED()
}
const { err } = disconnect(this)
if (err) {
throw err
}
}
/**
* Broadcasts a datagram on the socket. For connectionless sockets, the
* destination port and address must be specified. Connected sockets, on the
* other hand, will use their associated remote endpoint, so the port and
* address arguments must not be set.
*
* > The msg argument contains the message to be sent. Depending on its type,
* different behavior can apply. If msg is a Buffer, any TypedArray or a
* DataView, the offset and length specify the offset within the Buffer where
* the message begins and the number of bytes in the message, respectively.
* If msg is a String, then it is automatically converted to a Buffer with
* 'utf8' encoding. With messages that contain multi-byte characters, offset
* and length will be calculated with respect to byte length and not the
* character position. If msg is an array, offset and length must not be
* specified.
*
* > The address argument is a string. If the value of address is a host name,
* DNS will be used to resolve the address of the host. If address is not
* provided or otherwise nullish, '127.0.0.1' (for udp4 sockets) or '::1'
* (for udp6 sockets) will be used by default.
*
* > If the socket has not been previously bound with a call to bind, the socket
* is assigned a random port number and is bound to the "all interfaces"
* address ('0.0.0.0' for udp4 sockets, '::0' for udp6 sockets.)
*
* > An optional callback function may be specified to as a way of reporting DNS
* errors or for determining when it is safe to reuse the buf object. DNS
* lookups delay the time to send for at least one tick of the Node.js event
* loop.
*
* > The only way to know for sure that the datagram has been sent is by using a
* callback. If an error occurs and a callback is given, the error will be
* passed as the first argument to the callback. If a callback is not given,
* the error is emitted as an 'error' event on the socket object.
*
* > Offset and length are optional but both must be set if either are used.
* They are supported only when the first argument is a Buffer, a TypedArray,
* or a DataView.
*
* @param {Buffer | TypedArray | DataView | string | Array} msg - Message to be sent.
* @param {integer=} offset - Offset in the buffer where the message starts.
* @param {integer=} length - Number of bytes in the message.
* @param {integer=} port - Destination port.
* @param {string=} address - Destination host name or IP address.
* @param {Function=} callback - Called when the message has been sent.
* @see {@link https://nodejs.org/api/dgram.html#socketsendmsg-offset-length-port-address-callback}
*/
send (buffer, ...args) {
const id = this.id || rand64()
let offset = 0
let length
let port
let address
let cb = defaultCallback(this)
if (Array.isArray(buffer)) {
buffer = fromBufferList(buffer)
} else if (typeof buffer === 'string' || isArrayBufferView(buffer)) {
buffer = Buffer.from(buffer)
}
if (!Buffer.isBuffer(buffer)) {
throw new TypeError('Invalid buffer')
}
// detect callback at end of `args`
if (args.findIndex(isFunction) === args.length - 1) {
cb = args.pop()
}
// parse argument variants
if (typeof args[2] === 'number') {
[offset, length, port, address] = args
} else if (typeof args[1] === 'number') {
[offset, length] = args
} else if (typeof args[0] === 'number' && typeof args[1] === 'string') {
[port, address] = args
} else if (typeof args[0] === 'number') {
[port] = args
}
if (port !== undefined || this.state.connectState !== CONNECT_STATE_CONNECTED) {
// parse possible port as string
port = parseInt(port)
if (!Number.isInteger(port) || port <= 0 || port > (64 * 1024)) {
throw new ERR_SOCKET_BAD_PORT(
`Port should be > 0 and < 65536. Received ${port}.`
)
}
}
if (offset === undefined) {
offset = 0
}
if (length === undefined) {
length = buffer.length
}
if (!Number.isInteger(offset) || offset < 0) {
throw new RangeError(
`Offset should be >= 0 and < ${buffer.length} Received ${offset}.`
)
}
buffer = buffer.slice(offset)
if (!Number.isInteger(length) || length < 0 || length > buffer.length) {
throw new RangeError(
`Length should be >= 0 and <= ${buffer.length} Received ${length}.`
)
}
buffer = buffer.slice(0, length)
send(this, { id, port, address, buffer }, cb)
}
/**
* Close the underlying socket and stop listening for data on it. If a
* callback is provided, it is added as a listener for the 'close' event.
*
* @param {function=} callback - Called when the connection is completed or on error.
*
* @see {@link https://nodejs.org/api/dgram.html#socketclosecallback}
*/
close (cb) {
const state = getSocketState(this)
if (
!state || !(state.connected || state.bound) ||
(
this.state.bindState === BIND_STATE_UNBOUND &&
this.state.connectState === CONNECT_STATE_DISCONNECTED
)
) {
if (isFunction(cb)) {
cb(new ERR_SOCKET_DGRAM_NOT_RUNNING())
return
} else {
throw new ERR_SOCKET_DGRAM_NOT_RUNNING()
}
}
close(this, (err) => {
if (err) {
if (err.code === 'ERR_SOCKET_DGRAM_NOT_RUNNING') {
err = Object.assign(new ERR_SOCKET_DGRAM_NOT_RUNNING(), {
cause: err
})
}
if (isFunction(cb)) {
cb(err)
} else {
this.emit('error', err)
}
return
}
if (isFunction(cb)) {
cb(null)
}
this.emit('close')
})
return this
}
/**
*
* Returns an object containing the address information for a socket. For
* UDP sockets, this object will contain address, family, and port properties.
*
* This method throws EBADF if called on an unbound socket.
* @returns {Object} socketInfo - Information about the local socket
* @returns {string} socketInfo.address - The IP address of the socket
* @returns {string} socketInfo.port - The port of the socket
* @returns {string} socketInfo.family - The IP family of the socket
*
* @see {@link https://nodejs.org/api/dgram.html#socketaddress}
*/
address () {
if (this.state.bindState !== BIND_STATE_BOUND) {
throw new ERR_SOCKET_DGRAM_NOT_RUNNING()
}
if (!this.state.address) {
const result = getSockName(this)