# dgram

***

**1. Sending a UDP Packet with a Custom Port**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');
const data = Buffer.from('Hello there!');

socket.send(data, 0, data.length, 3000, 'localhost', (err) => {
  if (err) throw err;
  console.log('Packet sent to port 3000');
});
```

**2. Sending a UDP Packet with a Broadcast Address**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');
const data = Buffer.from('Hello everyone!');

// Use the broadcast address for all devices on the network
socket.send(data, 0, data.length, 5000, '255.255.255.255', (err) => {
  if (err) throw err;
  console.log('Packet sent to broadcast address');
});
```

**3. Receiving UDP Packets with a Custom Port**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');

socket.on('message', (msg, rinfo) => {
  console.log(`Received packet from ${rinfo.address}:${rinfo.port}: ${msg.toString()}`);
});

socket.on('error', (err) => {
  console.log(`Error: ${err}`);
});

socket.bind(3000);
```

**4. Receiving UDP Packets from a Specific Address**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');

socket.on('message', (msg, rinfo) => {
  if (rinfo.address === '192.168.1.100') {
    console.log(`Received packet from specified address: ${msg.toString()}`);
  }
});

socket.bind(3000);
```

**5. Sending Encrypted UDP Packets**

```js
const crypto = require('crypto');
const dgram = require('dgram');
const key = crypto.randomBytes(16);

const socket = dgram.createSocket('udp4');

socket.on('message', (msg, rinfo) => {
  const decipher = crypto.createDecipheriv('aes-128-cbc', key, rinfo.address);
  const decrypted = Buffer.concat([decipher.update(msg), decipher.final()]);
  console.log(`Received decrypted packet: ${decrypted.toString()}`);
});

socket.bind(3000);
```

**6. Receiving Encrypted UDP Packets**

```js
const crypto = require('crypto');
const dgram = require('dgram');
const key = crypto.randomBytes(16);

const socket = dgram.createSocket('udp4');

socket.on('message', (msg, rinfo) => {
  const cipher = crypto.createCipheriv('aes-128-cbc', key, rinfo.address);
  const encrypted = Buffer.concat([cipher.update(msg), cipher.final()]);
  socket.send(encrypted, rinfo.port, rinfo.address);
  console.log(`Sent encrypted packet to ${rinfo.address}:${rinfo.port}`);
});

socket.bind(3000);
```

**7. Creating a UDP Server with a Custom Port**

```js
const dgram = require('dgram');

const server = dgram.createSocket('udp4');

server.on('message', (msg, rinfo) => {
  console.log(`Received packet from ${rinfo.address}:${rinfo.port}: ${msg.toString()}`);
});

server.on('error', (err) => {
  console.log(`Error: ${err}`);
});

server.bind(3000);
```

**8. Creating a UDP Server with a Broadcast Address**

```js
const dgram = require('dgram');

const server = dgram.createSocket('udp4');

server.on('message', (msg, rinfo) => {
  if (rinfo.address === '255.255.255.255') {
    console.log(`Received packet from broadcast address: ${msg.toString()}`);
  }
});

server.bind(3000);
```

**9. Sending a UDP Packet with a TTL Value**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');
const data = Buffer.from('Hello there!');

socket.send(data, 0, data.length, 3000, 'localhost', {
  ttl: 2,
}, (err) => {
  if (err) throw err;
  console.log('Packet sent with TTL of 2');
});
```

**10. Receiving UDP Packets with a Specific TTL Value**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');

socket.on('message', (msg, rinfo) => {
  if (rinfo.ttl === 2) {
    console.log(`Received packet with TTL of 2: ${msg.toString()}`);
  }
});

socket.bind(3000);
```

**11. Sending a UDP Packet with a Multicast Address**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');
const data = Buffer.from('Hello multicast!');

// Use the multicast address for a specific group
socket.send(data, 0, data.length, 5000, '224.0.0.1', (err) => {
  if (err) throw err;
  console.log('Packet sent to multicast address');
});
```

**12. Receiving UDP Packets from a Multicast Address**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');

socket.on('message', (msg, rinfo) => {
  if (rinfo.address === '224.0.0.1') {
    console.log(`Received packet from multicast address: ${msg.toString()}`);
  }
});

// Join the multicast group
socket.addMembership('224.0.0.1');

socket.bind(5000);
```

**13. Sending a UDP Packet with a Specific Interface**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');
const data = Buffer.from('Hello interface!');

// Use the network interface with IP address '192.168.1.100'
socket.send(data, 0, data.length, 3000, 'localhost', {
  interface: '192.168.1.100',
}, (err) => {
  if (err) throw err;
  console.log('Packet sent through specific interface');
});
```

**14. Receiving UDP Packets from a Specific Interface**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');

socket.on('message', (msg, rinfo) => {
  if (rinfo.interface === '192.168.1.100') {
    console.log(`Received packet from specific interface: ${msg.toString()}`);
  }
});

// Bind to the network interface with IP address '192.168.1.100'
socket.bind(3000, '192.168.1.100');
```

**15. Pausing and Resuming UDP Socket**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');

// Pause the socket to stop receiving packets
socket.pause();

setTimeout(() => {
  // Resume the socket to start receiving packets again
  socket.resume();
}, 1000);
```

**16. Closing a UDP Socket**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');

// Close the socket to stop sending and receiving packets
socket.close();
```

**17. Broadcasting UDP Messages**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');
const data = Buffer.from('Broadcast message!');

// Set the broadcast flag to send packets to all devices on the network
socket.setBroadcast(true);

socket.send(data, 0, data.length, 3000, '255.255.255.255', (err) => {
  if (err) throw err;
  console.log('Broadcast message sent');
});
```

**18. Multicasting UDP Messages**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');
const data = Buffer.from('Multicast message!');

// Join a multicast group and set the multicast flag to send packets to all members
socket.addMembership('224.0.0.1');
socket.setMulticastTTL(128);

socket.send(data, 0, data.length, 3000, '224.0.0.1', (err) => {
  if (err) throw err;
  console.log('Multicast message sent');
});
```

**19. Sending UDP Messages with QoS Options**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');
const data = Buffer.from('Message with QoS!');

// Set the QoS options for the packet (e.g., for priority, reliability, etc.)
socket.setQoS({
  qos_marking: 0x04,
});

socket.send(data, 0, data.length, 3000, 'localhost', (err) => {
  if (err) throw err;
  console.log('Message with QoS sent');
});
```

**20. Receiving UDP Messages with QoS Options**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');

socket.on('message', (msg, rinfo) => {
  // Get the QoS options for the received packet
  const qos = socket.getQoS(rinfo);
  console.log(`Received QoS packet: ${msg.toString()}`);
  console.log(`QoS options: ${JSON.stringify(qos)}`);
});

socket.bind(3000);
```

**21. Creating a UDP Server with Multiple Bindings**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');
const data = Buffer.from('Multi-binding server message!');

// Bind to multiple IP addresses and ports
socket.bind([
  { address: '192.168.1.100', port: 3000 },
  { address: '192.168.1.200', port: 4000 },
]);

socket.on('message', (msg, rinfo) => {
  console.log(`Received packet from ${rinfo.address}:${rinfo.port}: ${msg.toString()}`);
});
```

**22. Creating a UDP Client with Multiple Connections**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');
const data = Buffer.from('Multi-connection client message!');

// Connect to multiple servers
socket.connect([
  { address: '192.168.1.100', port: 3000 },
  { address: '192.168.1.200', port: 4000 },
]);

socket.on('message', (msg, rinfo) => {
  console.log(`Received packet from ${rinfo.address}:${rinfo.port}: ${msg.toString()}`);
});

// Send data to all connected servers
socket.send(data, (err) => {
  if (err) throw err;
  console.log('Multi-connection data sent');
});
```

**23. Interfacing with DNS SRV Records for UDP**

```js
const dgram = require('dgram');
const dns = require('dns');
const socket = dgram.createSocket('udp4');
const data = Buffer.from('SRV query message!');

// Lookup a DNS SRV record to get the service address and port
dns.resolveSrv('example.com', 'udp', (err, records) => {
  if (err) throw err;

  // Send a UDP packet to the service address and port
  socket.send(data, 0, data.length, records[0].port, records[0].name, (err) => {
    if (err) throw err;
    console.log('SRV query data sent');
  });
});
```

**24. Using UDP for Simple Chat**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');

// Send a chat message to another client
socket.send(Buffer.from('Hello there!'), 3000, '192.168.1.100');

// Listen for incoming chat messages
socket.on('message', (msg, rinfo) => {
  console.log(`Received chat message from ${rinfo.address}:${rinfo.port}: ${msg.toString()}`);
});

socket.bind(3000);
```

**25. Building a Simple UDP File Transfer**

```js
const dgram = require('dgram');
const fs = require('fs');

// Create a UDP socket for sending files
const fileSocket = dgram.createSocket('udp4');

// Read the file to send
fs.readFile('file.txt', (err, data) => {
  if (err) throw err;

  // Send the file data in chunks
  for (let i = 0; i < data.length; i += 1024) {
    fileSocket.send(data.slice(i, i + 1024), 3000, '192.168.1.100');
  }

  // Send a termination message to indicate the end of the file transfer
  fileSocket.send(Buffer.from('EOF'), 3000, '192.168.1.100');
});
```

**26. Creating a UDP Proxy Server**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');

// Proxy incoming UDP packets to another server
socket.on('message', (msg, rinfo) => {
  const targetSocket = dgram.createSocket('udp4');

  targetSocket.send(msg, 0, msg.length, 3000, '192.168.1.200', (err) => {
    if (err) throw err;
  });
});

socket.bind(3000);
```

**27. Building a UDP Hole Punching Server**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');

// Keep track of client connections
const clients = {};

// Listen for incoming UDP packets
socket.on('message', (msg, rinfo) => {
  // Check if the client is already registered
  if (!clients[rinfo.address]) {
    clients[rinfo.address] = {};
  }

  const client = clients[rinfo.address];

  // Extract the message type
  const type = msg.toString().substr(0, 3);

  switch (type) {
    case 'REG':
      // Register the client and assign a unique port
      client.port = Math.floor(Math.random() * (65535 - 1024) + 1024);
      client.address = rinfo.address;
      break;
    case 'SES':
      // Establish a session with another client
      const targetAddress = msg.toString().substr(4);
      const targetClient = clients[targetAddress];

      // Send a message to the target client with the initiator's port and address
      const targetSocket = dgram.createSocket('udp4');
      targetSocket.send(Buffer.from(`SES ${client.port} ${client.address}`), 0, 17, targetClient.port, targetClient.address);
      break;
    default:
      break;
  }
});

socket.bind(3000);
```

**28. Implementing a UDP-Based Remote Control**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');

// Send control commands to a remote device
socket.send(Buffer.from('UP 50'), 0, 6, 3000, '192.168.1.100');

// Listen for incoming feedback from the remote device
socket.on('message', (msg, rinfo) => {
  console.log(`Received feedback from ${rinfo.address}:${rinfo.port}: ${msg.toString()}`);
});

socket.bind(3000);
```

**29. Using UDP for Real-time Data Streaming**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');

// Send real-time data to clients
setInterval(() => {
  socket.send(Buffer.from('Realtime data: ' + Date.now()), 0, 20, 3000, '255.255.255.255');
}, 500);
```

**30. Building a UDP-Based Network Monitor**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');

// Periodically send and receive UDP packets to monitor network connectivity
setInterval(() => {
  socket.send(Buffer.from('PING'), 0, 4, 3000, '255.255.255.255');

  socket.on('message', (msg, rinfo) => {
    if (msg.toString() === 'PONG') {
      console.log(`Received PONG from ${rinfo.address}:${rinfo.port}`);
    }
  });
}, 500);

socket.bind(3000);
```

**31. Creating a UDP-Based Web Server**

```js
const dgram = require('dgram');
const http = require('http');

// Create a UDP socket to listen for HTTP requests
const socket = dgram.createSocket('udp4');

// Create an HTTP server to handle the requests
const server = http.createServer((req, res) => {
  res.writeHead(200);
  res.end('Hello from UDP!');
});

// Listen for UDP packets and forward them to the HTTP server
socket.on('message', (msg, rinfo) => {
  const request = http.request(req, res => {
    const response = Buffer.from(res.statusCode + ' ' + res.statusMessage + '\n\n');
    response.write(res.body);
    socket.send(response, 0, response.length, rinfo.port, rinfo.address);
  });

  request.end(msg);
});

socket.bind(3000);
```

**32. Implementing a UDP-Based Game Server**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');

// Listen for incoming game updates from clients
socket.on('message', (msg, rinfo) => {
  // Parse the game update message
  const update = JSON.parse(msg.toString());

  // Update the game state based on the received update
  gameState[update.playerId] = update.position;
});

// Broadcast the updated game state to all clients
setInterval(() => {
  socket.send(Buffer.from(JSON.stringify(gameState)), 0, 20, 3000, '255.255.255.255');
}, 50);

socket.bind(3000);
```

**33. Building a UDP-Based Chat Server**

```js
const dgram = require('dgram');
const socket = dgram.createSocket('udp4');

// Keep track of connected clients
const clients = {};

// Listen for incoming chat messages
socket.on('message', (msg, rinfo) => {
  // Check if the client is already registered
  if (!clients[rinfo.address]) {
    clients[rinfo.address] = { name: rinfo.address };
  }

  const client = clients[rinfo.address];

  // Broadcast the chat message to all connected clients
  for (const address in clients) {
    if (address !== rinfo.address) {
      socket.send(Buffer.from(`${client.name}: ${msg.toString()}`), 0, 20, 3000, address);
    }
  }
});

socket.bind(3000);
```

**34. Implementing a UDP-Based Video Streaming Server**

```js
const dgram = require('dgram');
const fs = require('fs');

// Create a UDP socket to send video frames
const socket = dgram.createSocket('udp4');

// Open the video file
const videoStream = fs.createReadStream('video.mp4');

// Send video frames in chunks
videoStream.on('data', (chunk) => {
  socket.send(chunk, 0, chunk.length, 3000, '255.255.255.255');
});
```

**35. Building a UDP-Based File Transfer Client**

```js
const dgram = require('dgram');
const fs = require('fs');

// Create a UDP socket to receive files
const socket = dgram.createSocket('udp4');

// Keep track of incoming file data
const fileData = [];

// Listen for incoming file data
socket.on('message', (msg, rinfo) => {
  // Check if the message is the end of the file transmission
  if (msg.toString() === 'EOF') {
    // Write the file data to disk
    fs.writeFileSync('received_file.txt', Buffer.concat(fileData));
  } else {
    // Append the file data to the buffer
    fileData.push(msg);
  }
});

socket.bind(3000);
```

**36. Implementing a UDP-Based Voice over IP (VoIP) System**

```js
const dgram = require('dgram');
const opus = require('node-opus');

// Create a UDP socket for sending audio packets
const socket = dgram.createSocket('udp4');

// Create an Opus encoder
const encoder = new opus.Encoder({ samplingRate: 48000, channels: 1 });

// Encode and send audio packets
setInterval(() => {
  const audioBuffer = Buffer.from('Audio data');
  const encodedAudio = encoder.encode(audioBuffer);
  socket.send(encodedAudio, 0, encodedAudio.length, 3000, '192.168.1.100');
}, 20);
```
