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
// Node.js dgram API
// Minimal implementation compatible with Node.js
// https://nodejs.org/api/dgram.html
'use strict';
// eslint-disable-next-line no-unused-expressions
(({ dgramCreateSocket, dgramBind, dgramSend, dgramClose, dgramAddress, dgramSetBroadcast, dgramSetTTL, dgramSetMulticastTTL, dgramSetMulticastLoopback, dgramAddMembership, dgramDropMembership, dgramRecv, dgramRegisterForMessages, dgramUnregisterForMessages, dgramRef, dgramUnref }) => {
/**
* Socket class - represents a UDP socket
* Extends EventTarget to provide event-based API
*/
class Socket extends EventTarget {
#type;
#socket = null;
#bound = false;
#closed = false;
#recvBufferSize = 65536;
#sendBufferSize = 65536;
#socketId = null; // ID for event loop registration
#isRef = true; // Whether this socket keeps the event loop alive
constructor(options) {
super();
if (typeof options === 'string') {
this.#type = options;
} else if (options && typeof options === 'object') {
this.#type = options.type || 'udp4';
if (options.recvBufferSize) {
this.#recvBufferSize = options.recvBufferSize;
}
if (options.sendBufferSize) {
this.#sendBufferSize = options.sendBufferSize;
}
} else {
throw new TypeError('Invalid options');
}
if (this.#type !== 'udp4' && this.#type !== 'udp6') {
throw new TypeError("Bad socket type specified. Valid types are: udp4, udp6");
}
// Create the underlying socket type identifier
dgramCreateSocket(this.#type);
}
/**
* Binds the socket to a port and optional address
* @param {number} port - Port to bind to (0 for OS-assigned)
* @param {string} [address] - Address to bind to
* @param {Function} [callback] - Called when binding is complete
* @returns {Socket} this
*/
bind(port, address, callback) {
if (this.#closed) {
throw new Error('Socket is closed');
}
if (this.#bound) {
throw new Error('Socket is already bound');
}
// Handle different argument patterns
if (typeof port === 'object' && port !== null) {
// bind({ port, address, exclusive }, callback)
const options = port;
callback = address;
port = options.port || 0;
address = options.address;
} else if (typeof port === 'function') {
// bind(callback)
callback = port;
port = 0;
address = undefined;
} else if (typeof address === 'function') {
// bind(port, callback)
callback = address;
address = undefined;
}
try {
this.#bindInternal(port || 0, address);
// Emit listening event asynchronously
queueMicrotask(() => {
const event = new Event('listening');
this.dispatchEvent(event);
if (callback) {
callback();
}
});
} catch (err) {
queueMicrotask(() => {
const errorEvent = new Event('error');
errorEvent.error = err;
this.dispatchEvent(errorEvent);
if (callback) {
callback(err);
}
});
}
return this;
}
/**
* Internal bind implementation (synchronous, no events)
* @param {number} port - Port to bind to
* @param {string} [address] - Address to bind to
*/
#bindInternal(port, address) {
this.#socket = dgramBind(this.#type, port, address);
this.#bound = true;
// Register the socket for message callbacks from the event loop
// This callback will be called when data is received
this.#socketId = dgramRegisterForMessages(this.#socket, (data, rinfo) => {
// Wrap the Uint8Array data in a Buffer for Node.js compatibility
// Node.js dgram message event passes a Buffer, not a Uint8Array
const bufferData = globalThis.Buffer ? globalThis.Buffer.from(data) : data;
// Dispatch the message event
const event = new Event('message');
event.data = bufferData;
event.rinfo = rinfo;
this.dispatchEvent(event);
});
// Apply ref/unref state
if (!this.#isRef) {
dgramUnref(this.#socketId);
}
}
/**
* Sends a message through the socket
* @param {Buffer|string|Array} msg - Message to send
* @param {number} [offset] - Offset in buffer
* @param {number} [length] - Length of message
* @param {number} port - Destination port
* @param {string} [address] - Destination address
* @param {Function} [callback] - Called when message is sent
*/
send(msg, offset, length, port, address, callback) {
if (this.#closed) {
throw new Error('Socket is closed');
}
// Handle different argument patterns
// Pattern 1: send(msg, port, address, callback) - offset is actually port, length is address
if (typeof offset === 'number' && typeof length === 'string') {
callback = typeof port === 'function' ? port : undefined;
address = length;
port = offset;
offset = 0;
length = undefined;
}
// Pattern 2: send(msg, port, callback) - offset is port, length is callback
else if (typeof offset === 'number' && typeof length === 'function') {
callback = length;
address = undefined;
port = offset;
offset = 0;
length = undefined;
}
// Pattern 3: send(msg, port) - offset is port, no callback
else if (typeof offset === 'number' && length === undefined) {
port = offset;
address = undefined;
offset = 0;
length = undefined;
}
// Default address based on socket type
if (!address) {
address = this.#type === 'udp6' ? '::1' : '127.0.0.1';
}
// Convert message to appropriate format
let buffer;
if (typeof msg === 'string') {
buffer = new TextEncoder().encode(msg);
} else if (msg instanceof Uint8Array) {
buffer = msg;
} else if (Array.isArray(msg)) {
// Concatenate array of buffers
const totalLength = msg.reduce((acc, buf) => acc + buf.length, 0);
buffer = new Uint8Array(totalLength);
let pos = 0;
for (const buf of msg) {
const data = typeof buf === 'string' ? new TextEncoder().encode(buf) : buf;
buffer.set(data, pos);
pos += data.length;
}
offset = 0;
length = buffer.length;
} else {
throw new TypeError('Invalid message type');
}
// Set default offset and length if not specified
if (offset === undefined || offset === 0) {
offset = 0;
}
if (length === undefined) {
length = buffer.length;
}
// Auto-bind if not bound (use internal method)
if (!this.#bound) {
this.#bindInternal(0, undefined);
}
try {
const bytesSent = dgramSend(this.#socket, buffer, offset || 0, length || buffer.length, port, address);
if (callback) {
queueMicrotask(() => callback(null, bytesSent));
}
} catch (err) {
if (callback) {
queueMicrotask(() => callback(err));
} else {
const errorEvent = new Event('error');
errorEvent.error = err;
this.dispatchEvent(errorEvent);
}
}
}
/**
* Closes the socket
* @param {Function} [callback] - Called when socket is closed
*/
close(callback) {
if (this.#closed) {
if (callback) {
queueMicrotask(() => callback());
}
return;
}
this.#closed = true;
// Unregister from event loop first
if (this.#socketId !== null) {
try {
dgramUnregisterForMessages(this.#socketId);
} catch (err) {
// Ignore unregister errors
}
this.#socketId = null;
}
if (this.#socket) {
try {
dgramClose(this.#socket);
} catch (err) {
// Ignore close errors
}
this.#socket = null;
}
queueMicrotask(() => {
const event = new Event('close');
this.dispatchEvent(event);
if (callback) {
callback();
}
});
}
/**
* Returns the address information of the socket
* @returns {{ address: string, family: string, port: number }}
*/
address() {
if (!this.#bound) {
throw new Error('Socket is not bound');
}
if (this.#closed) {
throw new Error('Socket is closed');
}
return dgramAddress(this.#socket);
}
/**
* Sets or clears the SO_BROADCAST socket option
* @param {boolean} flag
*/
setBroadcast(flag) {
if (!this.#bound) {
throw new Error('Socket is not bound');
}
if (this.#closed) {
throw new Error('Socket is closed');
}
dgramSetBroadcast(this.#socket, flag);
}
/**
* Sets the IP_TTL socket option
* @param {number} ttl
*/
setTTL(ttl) {
if (!this.#bound) {
throw new Error('Socket is not bound');
}
if (this.#closed) {
throw new Error('Socket is closed');
}
if (typeof ttl !== 'number' || ttl < 1 || ttl > 255) {
throw new RangeError('TTL must be between 1 and 255');
}
dgramSetTTL(this.#socket, ttl);
}
/**
* Sets the IP_MULTICAST_TTL socket option
* @param {number} ttl
*/
setMulticastTTL(ttl) {
if (!this.#bound) {
throw new Error('Socket is not bound');
}
if (this.#closed) {
throw new Error('Socket is closed');
}
if (typeof ttl !== 'number' || ttl < 0 || ttl > 255) {
throw new RangeError('Multicast TTL must be between 0 and 255');
}
dgramSetMulticastTTL(this.#socket, ttl);
}
/**
* Sets or clears the IP_MULTICAST_LOOP socket option
* @param {boolean} flag
*/
setMulticastLoopback(flag) {
if (!this.#bound) {
throw new Error('Socket is not bound');
}
if (this.#closed) {
throw new Error('Socket is closed');
}
dgramSetMulticastLoopback(this.#socket, flag);
}
/**
* Joins a multicast group
* @param {string} multicastAddress - Multicast group address
* @param {string} [multicastInterface] - Interface to use
*/
addMembership(multicastAddress, multicastInterface) {
if (!this.#bound) {
throw new Error('Socket is not bound');
}
if (this.#closed) {
throw new Error('Socket is closed');
}
dgramAddMembership(this.#socket, multicastAddress, multicastInterface);
}
/**
* Leaves a multicast group
* @param {string} multicastAddress - Multicast group address
* @param {string} [multicastInterface] - Interface to use
*/
dropMembership(multicastAddress, multicastInterface) {
if (!this.#bound) {
throw new Error('Socket is not bound');
}
if (this.#closed) {
throw new Error('Socket is closed');
}
dgramDropMembership(this.#socket, multicastAddress, multicastInterface);
}
/**
* Returns the receive buffer size
* @returns {number}
*/
getRecvBufferSize() {
return this.#recvBufferSize;
}
/**
* Sets the receive buffer size
* @param {number} size
*/
setRecvBufferSize(size) {
if (typeof size !== 'number' || size < 1) {
throw new RangeError('Buffer size must be a positive number');
}
this.#recvBufferSize = size;
}
/**
* Returns the send buffer size
* @returns {number}
*/
getSendBufferSize() {
return this.#sendBufferSize;
}
/**
* Sets the send buffer size
* @param {number} size
*/
setSendBufferSize(size) {
if (typeof size !== 'number' || size < 1) {
throw new RangeError('Buffer size must be a positive number');
}
this.#sendBufferSize = size;
}
/**
* Reference the socket (keeps event loop alive)
* @returns {Socket} this
*/
ref() {
this.#isRef = true;
if (this.#socketId !== null) {
dgramRef(this.#socketId);
}
return this;
}
/**
* Unreference the socket (allows event loop to exit)
* @returns {Socket} this
*/
unref() {
this.#isRef = false;
if (this.#socketId !== null) {
dgramUnref(this.#socketId);
}
return this;
}
/**
* Receive data from the socket (non-blocking)
* This is used internally for polling
* @returns {{ data: Uint8Array, rinfo: { address, family, port, size } } | null}
*/
_recv() {
if (!this.#bound || this.#closed || !this.#socket) {
return null;
}
return dgramRecv(this.#socket);
}
// Node.js style event methods for compatibility
on(event, listener) {
this.addEventListener(event, (e) => {
if (event === 'message') {
listener(e.data, e.rinfo);
} else if (event === 'error') {
listener(e.error);
} else {
listener(e);
}
});
return this;
}
once(event, listener) {
this.addEventListener(event, (e) => {
if (event === 'message') {
listener(e.data, e.rinfo);
} else if (event === 'error') {
listener(e.error);
} else {
listener(e);
}
}, { once: true });
return this;
}
off(event, listener) {
this.removeEventListener(event, listener);
return this;
}
removeListener(event, listener) {
return this.off(event, listener);
}
removeAllListeners(event) {
// Note: This is a simplified implementation
// Full implementation would track all listeners
return this;
}
}
/**
* Creates a dgram.Socket
* @param {string|Object} options - Socket type ('udp4' or 'udp6') or options object
* @param {Function} [callback] - Listener for 'message' event
* @returns {Socket}
*/
function createSocket(options, callback) {
const socket = new Socket(options);
if (callback) {
socket.on('message', callback);
}
return socket;
}
// Export the dgram module
const dgram = {
createSocket,
Socket,
};
// Make it available via import
globalThis.__node_modules = globalThis.__node_modules || {};
globalThis.__node_modules['node:dgram'] = dgram;
globalThis.__node_modules['dgram'] = dgram;
});