Language: EN

comunicacion-udp-nodejs

How to do UDP communications with Node.js and the dgram module

UDP (User Datagram Protocol) is a connectionless, datagram-oriented communication protocol that allows for fast and efficient data transmission between devices on a network.

Unlike TCP, UDP does not guarantee packet delivery or reception order, making it suitable for applications that prioritize speed and simplicity over absolute reliability.

Some of its features are:

  • Direct communication: UDP facilitates data transmission between systems without the overhead of establishing and maintaining a persistent connection.
  • Low Latency: By minimizing the process of establishing and closing connections, UDP significantly reduces latency compared to other protocols.

UDP communication finds application in a variety of scenarios, from real-time video transmission to the implementation of online game protocols.

Example of UDP implementation in Node.js

In Node.js, we can create UDP servers using the dgram module. Below, we will explore an example of how to create a UDP server in Node.js and understand each part of the code.

Let’s see it with a usage example

import dgram from 'dgram';

// Create a UDP server
const server = dgram.createSocket('udp4');

// Event when receiving a message
server.on('message', (msg, rinfo) => {
  console.log(`Message received from ${rinfo.address}:${rinfo.port} - Content: ${msg}`);

  // Respond to the client
  server.send('Message received by the server', rinfo.port, rinfo.address, (err) => {
    if (err) {
      console.error('Error sending message:', err);
    } else {
      console.log('Response sent to the client');
    }
  });
});

// Event when the server is ready and listening
server.on('listening', () => {
  const address = server.address();
  console.log(`UDP server started at ${address.address}:${address.port}`);
});

// Handle errors
server.on('error', (err) => {
  console.error('Error in UDP server:', err);
  server.close();
});

const port = 3000;
server.bind(port);

In this example:

  • We import the dgram module, which allows us to work with UDP in Node.js.
  • We create a UDP server using dgram.createSocket('udp4').
  • Then, we send a response message to the client using server.send().
  • We define several event handlers for the UDP server:
    • message: This event is triggered when the server receives a message. In this case, we print the sender’s IP address and port (rinfo.address and rinfo.port, respectively), as well as the message content (msg). Then, we send a response message to the client using server.send().
    • listening: This event is triggered when the server is ready and listening on the specified port. Here, we get the server’s IP address and port and print it to the console to indicate that the server has been started successfully.
    • error: This event is triggered when an error occurs in the UDP server. In this case, we print the error to the console and close the server.