راهنمای جامع UDP / Datagram Sockets در Node.js

ماژول node:dgram پیاده‌سازی کامل سوکت‌های UDP را در Node.js فراهم می‌کند. UDP یک پروتکل سبک، بدون اتصال (connectionless) و مناسب برای برنامه‌های بلادرنگ مانند VoIP، بازی‌ها، IoT، سیستم‌های پخش (broadcast) و چندپخشی (multicast) است. این ماژول امکان ساخت سوکت، ارسال و دریافت دیتاگرام، مدیریت TTL، عضویت در گروه‌های multicast، کنترل بافرها، و مدیریت رفتار سطح پایین شبکه را فراهم می‌کند.

UDP / Datagramdgram.Socketsocket.bind / socket.sendMulticast / BroadcastTTL / Buffer sizes

~2 دقیقه مطالعه · آخرین به‌روزرسانی ۹ دی ۱۴۰۴

1. معرفی


ماژول node:dgram امکان کار با پروتکل UDP را در Node.js فراهم می‌کند. این ماژول از IPv4 و IPv6 پشتیبانی کرده و قابلیت‌های multicast، broadcast و سوکت‌های UDP متصل (connected) را ارائه می‌دهد.


2. ساخت سوکت UDP


const dgram = require('node:dgram');
const server = dgram.createSocket('udp4');

3. رویدادهای اصلی سوکت


3.1 'error'


در صورت بروز هر خطا روی سوکت فراخوانی می‌شود.

3.2 'message'


هنگامی که دیتاگرامی دریافت شود، این رویداد فعال می‌شود.

3.3 'listening'


پس از bind شدن سوکت و آماده شدن برای دریافت پیام.

3.4 'close'


پس از بسته شدن سوکت.

3.5 'connect'


پس از اتصال موفق سوکت UDP به مقصد.


4. bind کردن سوکت


برای دریافت پیام، سوکت باید bind شود:

socket.bind(41234);

5. ارسال دیتاگرام


UDP می‌تواند Buffer، رشته، TypedArray، DataView یا آرایه‌ای از Bufferها را ارسال کند.


5.1 ارسال بدون اتصال (Connectionless)


client.send(message, 41234, 'localhost');

5.2 ارسال با سوکت متصل (Connected UDP)


client.connect(41234, 'localhost', () => {
  client.send(message);
});

6. پشتیبانی Multicast


6.1 عضویت در گروه Multicast


socket.addMembership('224.0.0.114');

6.2 Multicast مبتنی بر منبع (Source-Specific)


socket.addSourceSpecificMembership(source, group);

6.3 خروج از گروه


socket.dropMembership(address);
socket.dropSourceSpecificMembership(source, group);

7. Broadcast


socket.setBroadcast(true);

8. مدیریت بافر و صف ارسال


  • socket.getRecvBufferSize()
  • socket.getSendBufferSize()
  • socket.setRecvBufferSize(size)
  • socket.setSendBufferSize(size)
  • socket.getSendQueueSize()
  • socket.getSendQueueCount()

9. TTL و Multicast TTL


  • socket.setTTL(ttl): برای unicast
  • socket.setMulticastTTL(ttl): برای multicast

10. انتخاب رابط Multicast


برای تعیین رابط خروجی بسته‌های multicast:

socket.setMulticastInterface('10.0.0.2'); // IPv4
socket.setMulticastInterface('::%eth0');  // IPv6

11. ref و unref


کنترل اینکه سوکت فرآیند Node.js را زنده نگه دارد یا نه:

socket.unref();
socket.ref();

12. BlockList


برای مسدود کردن IPها یا محدوده‌های خاص:

receiveBlockList: new net.BlockList()
sendBlockList: new net.BlockList()

13. پشتیبانی AbortSignal


بستن سوکت با AbortController:

const controller = new AbortController();
const server = dgram.createSocket({ type: 'udp4', signal: controller.signal });
controller.abort();

14. محدودیت اندازه دیتاگرام


  • حداکثر تئوری: ~65KB
  • MTU معمول IPv4: حدود 576 بایت
  • حداقل MTU IPv6: 1280 بایت

15. dgram.createSocket()


گزینه‌های مهم:

  • type: 'udp4' یا 'udp6'
  • reuseAddr / reusePort
  • ipv6Only
  • recvBufferSize / sendBufferSize
  • lookup سفارشی
  • signal برای Abort
  • receiveBlockList / sendBlockList

نتیجه‌گیری


ماژ

نوشته و پژوهش‌شده توسط دکتر شاهین صیامی

مقالات مرتبط

Comprehensive Guide to the Node.js VM Module (node:vm)

The node:vm module allows you to compile and execute JavaScript code inside isolated V8 contexts — essentially creating lightweight sandboxes within your Node.js application. These contexts have their own global scope and can run code independently from the main environment. However, vm is NOT a security sandbox. It is powerful for dynamic code execution, template engines, REPLs, plugin systems, and controlled module execution, but it must never be used to run untrusted code.

ادامه

Comprehensive Guide to the V8 Module in Node.js (node:v8)

The node:v8 module exposes low-level APIs that interact directly with the V8 JavaScript engine embedded in Node.js. . These APIs provide access to heap statistics, heap snapshots, coverage tools, serialization mechanisms, V8 flags, object queries, and promise lifecycle hooks. The module is essential for performance analysis, memory debugging, tooling, and advanced Node.js internals work.

ادامه

Comprehensive Guide to Node.js Worker Threads (node:worker_threads)

The node:worker_threads module enables true multithreading in Node.js by running JavaScript in separate threads. While Node.js is traditionally single‑threaded, worker threads allow CPU‑intensive tasks to run in parallel without blocking the event loop. They support shared memory, zero‑copy transfers, worker pools, resource limits, and advanced synchronization APIs. Worker threads are ideal for heavy computation, data processing, and parallel workloads—while async I/O remains best handled by the main thread.

ادامه

Comprehensive Guide to the Node.js util Module (node:util)

The node:util module provides a powerful collection of helper functions used throughout Node.js core and extremely useful for application developers. These utilities support debugging, inspection, formatting, type checking, callback/Promise conversions, argument parsing, text encoding, MIME handling, and more. It is one of the most versatile and essential toolkits in the Node.js ecosystem.

ادامه

Comprehensive Guide to the URL Module in Node.js

The node:url module provides tools for parsing, constructing, and manipulating URLs. Node.js supports two URL APIs: WHATWG URL API — modern, browser‑compatible, standards‑based. Legacy Node.js URL API — older, Node‑specific, now discouraged. The WHATWG API is the recommended approach for all modern applications. It provides a clean, consistent interface for working with URL components, query parameters, and structured URL patterns.

ادامه

Comprehensive Guide to Trace Events and TTY in Node.js

Node.js provides two powerful low‑level modules for diagnostics and terminal interaction: node:trace_events — a high‑resolution tracing system that captures internal activity from V8, Node.js core, and userland code. It is essential for profiling, performance analysis, and deep debugging. node:tty — a module that exposes TTY (terminal) interfaces, enabling advanced CLI tools, raw input handling, cursor control, color detection, and terminal resizing. This guide explains both modules in a clean, structured, and practical way.

ادامه