Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Node.js dgram Module

Node.js dgram Module in Detail

Java FileNode.js Built-in Modules


Node.js's dgram The module provides an implementation of UDP (User Datagram Protocol) datagram sockets. UDP is a connectionless transport layer protocol. Unlike TCP, it does not guarantee reliable data delivery, but offers lower latency and higher transmission efficiency.

Main Features


Core API Analysis

1. Creating a Socket

Example

const

dgram

=

require

(

'dgram'

)

;

// Create a UDP socket

const

socket

=

dgram.

createSocket

(

'udp4'

)

;

// IPv4

// or

const

socket

=

dgram.

createSocket

(

'udp6'

)

;

// IPv6

Parameter Description


2. Binding a Port

Example

socket.

bind

(

41234

,

(

)

=>

{

  console.

log

(

'Socket is listening on port 41234'

)

;

}

)

;

Optional arguments


3. Sending Messages

Example

const

message

=

Buffer.

from

(

'Hello UDP!'

)

;

const

port

=

41234

;

const

host

=

'127.0.0.1'

;

socket.

send

(

message

,

port

,

host

,

(

err

)

=>

{

 

if

(

err

)

throw

err

;

  console.

log

(

'Message sent'

)

;

}

)

;

Parameter Description

  1. msg: The message to send (Buffer, String, or Array)
  2. offset: The offset of the message within the Buffer
  3. length: The number of bytes in the message
  4. port: The destination port
  5. address: The destination address
  6. callback: The callback invoked after sending completes

4. Receiving Messages

Example

socket.

on

(

'message'

,

(

msg

,

rinfo

)

=>

{

  console.

log

(

`Received $

{

msg.

length

}

bytes from $

{

rinfo.

address

}

:

$

{

rinfo.

port

}

`

)

;

  console.

log

(

`Message content

:

$

{

msg.

toString

(

)

}

`

)

;

}

)

;

Callback Parameters

- `address`: Sender IP - `port`: Sender port - `family`: IP address family (IPv4/IPv6) - `size`: Message size (in bytes)

5. Closing a Socket

Example

socket.

close

(

(

)

=>

{

  console.

log

(

'Socket closed'

)

;

}

)

;

Notes


Event Handling

dgram A socket is an EventEmitter and can listen for the following events:

1. The 'message' Event

Emitted when a new datagram is received

2. The 'listening' Event

Emitted when the socket starts listening

3. The 'close' Event

Emitted when the socket is closed

4. The 'error' Event

Emitted when an error occurs

Example

socket.

on

(

'error'

,

(

err

)

=>

{

  console.

error

(

`Socket error

:

\n$

{

err.

stack

}

`

)

;

  socket.

close

(

)

;

}

)

;


Practical Application Scenarios

1. Real-Time Games

Leveraging UDP's low-latency characteristics to transmit game state updates

2. Video/Audio Streaming

Scenarios that tolerate a small amount of data loss but require low latency

3. DNS Queries

The DNS protocol typically uses UDP

4. Network Discovery Protocols

such as SSDP (Simple Service Discovery Protocol)


Complete example

UDP Server

Example

const

dgram

=

require

(

'dgram'

)

;

const

server

=

dgram.

createSocket

(

'udp4'

)

;

server.

on

(

'message'

,

(

msg

,

rinfo

)

=>

{

  console.

log

(

`Server got

:

$

{

msg

}

from $

{

rinfo.

address

}

:

$

{

rinfo.

port

}

`

)

;

}

)

;

server.

on

(

'listening'

,

(

)

=>

{

 

const

address

=

server.

address

(

)

;

  console.

log

(

`Server listening $

{

address.

address

}

:

$

{

address.

port

}

`

)

;

}

)

;

server.

bind

(

41234

)

;

UDP Client

Example

const

dgram

=

require

(

'dgram'

)

;

const

client

=

dgram.

createSocket

(

'udp4'

)

;

const

message

=

Buffer.

from

(

'Hello UDP Server'

)

;

client.

send

(

message

,

41234

,

'localhost'

,

(

err

)

=>

{

 

if

(

err

)

throw

err

;

  console.

log

(

'Message sent'

)

;

  client.

close

(

)

;

}

)

;


Notes

  1. Message Size Limit: A UDP datagram is at most 65507 bytes (IPv4)
  2. Reliability: The application layer needs to implement retransmission and acknowledgment mechanisms
  3. Safety: UDP is vulnerable to IP spoofing and DDoS attacks
  4. Firewall: Ensure the firewall allows UDP traffic

Performance Optimization Suggestions

  1. Reuse socket addresses (SO_REUSEADDR)
  2. Adjust the receive buffer size appropriately
  3. Process messages in batches to reduce system calls
  4. Consider using setRecvBufferSize() and setSendBufferSize()

Summary

Node.js's dgram The module provides developers with powerful UDP network programming capabilities, especially suited for network application scenarios that require low latency and high efficiency. Although UDP does not provide reliability guarantees, this trade-off is acceptable in many real-time applications. Understanding UDP's characteristics and the dgram module's API can help developers build more efficient network applications.

Java FileNode.js Built-in Modules