UDP

Learn how the UDP module works in Node.js.

UDP

Alongside TCP, UDPUser Datagram Protocol is the other most common communication protocol. It provides a simple and lightweight connectionless communication model. Being connectionless, a very minimal amount of protocol mechanisms come into play when sending packets. While checksums are still used for data integrity, UDP is favored in real-time applications, as it avoids the overhead of setting up a connection, error-checking, and retransmission delays.

The dgram module

The dgram module provides an implementation of UDP Datagram sockets. These sockets are required for UDP communication.

const dgram = require("dgram");

const server = dgram.createSocket("udp4");
const port = 3500;

server.on("message", (data, rinfo) => {
  console.log(`Msg from client at port: ${rinfo.port}: ${data}`);
  server.send("Hello from server", rinfo.port, "localhost");
});

server.on("listening", function () {
  console.log("Server is listening on port", port);
});

server.on("close", function (err) {
  if (err) {
    console.log("Client disconnected due to error");
  } else {
    console.log("Client disconnected");
  }
  server.close();
});

server.bind(port);
Use ctrl + b, followed by a direction key, to switch panes in the terminal

The server-side

  • We import the dgram module on line 1.
  • The createSocket method on line 3 creates a UDP socket. A type must be passed; we are using udp4 in our case. The socket returned is an object of the EventEmitter class. This allows us to use the on method to handle
...