Language: EN

comunicacion-udp-nodejs

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

UDP (User Datagram Protocol) is a communication protocol oriented to datagrams that allows data transmission between devices on a network quickly and efficiently.

Unlike TCP, UDP does not guarantee packet delivery or order of reception, 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 protocols.

UDP communication finds its application in a variety of scenarios, from real-time video streaming to the implementation of online gaming 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 on 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 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 that 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 content of the message (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 obtain the server’s IP address and port and print it to the console to inform 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.

Download the Code

All the code from this post is available for download on Github. github-full