Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
Node.js new Agent() Method
Next article icon

Node.js UDP/DataGram Module

Last Updated : 26 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The UDP/Datagram module in Node.js helps you create apps that send and receive messages over a network using the User Datagram Protocol (UDP). Unlike other protocols, UDP doesn't need a connection to be set up before sending data, which makes it really fast and efficient. This is especially useful for things like streaming videos, online gaming, or sending messages to a bunch of people at once.

UDP/Datagram Module in Node.js

The UDP/Datagram module in Node.js is a handy tool for setting up UDP servers and clients. It allows you to send and receive messages without slowing down other processes, thanks to its non-blocking, asynchronous design. Best of all, it's built right into Node.js, so you can use it straight away without any extra installations.

Installation Step (Optional)

Installation is an optional step as it is an inbuilt Node.js module. However, if needed, you can install the module using the following command:

npm install dgram

Importing the Module

To use the UDP/Datagram module in your Node.js application, you need to import it as follows:

const dgram = require('dgram');

Explore this Node.js UDP/Datagram Module Complete Reference to discover detailed explanations, advanced usage examples, and expert tips for mastering its powerful features to enhance your Node.js development.

Features

  • Connectionless Communication: The UDP/Datagram module lets you send messages without needing to set up a connection, which makes it faster and better suited for applications that require quick communication.
  • Broadcasting: This module enables you to send messages to multiple clients at once, making it great for broadcasting information.
  • Low Latency: The UDP/Datagram module is perfect for applications that need quick response times, like online games or real-time video and audio streaming.

UDP Methods

The UDP/Datagram module provides several methods for creating and managing UDP communication. Here’s a summary of the key methods:

Method

Description

socket.close()

Closes the socket, stopping it from receiving any more messages.

socket.on('message')

Listens for messages sent to the socket.

dgram.createSocket()

Creates a new UDP socket.

socket.bind()

Binds the socket to a specific port and IP address.

socket.send()

Sends a message to a specified port and address.

Example 1: This example demonstrates how to create a UDP client that sends a message to the server and handles the server’s response.

JavaScript
console.clear();
const dgram = require('dgram');
const client = dgram.createSocket('udp4');
const message = Buffer.from('Hello from client');

client.send(message, 41234, 'localhost', (err) => {
    if (err) {
        console.log('Error:', err);
    } else {
        console.log('Message sent');
    }
});

client.on('message', (msg, rinfo) => {
    console.log(`Client received: ${msg} from ${rinfo.address}:${rinfo.port}`);
    client.close();
});

Output:

Screenshot-2024-08-25-203511
Output

Example 2: This example demonstrates a basic UDP client that sends a message to a server and a UDP server that listens for messages.

UDP Server Code

This code sets up a UDP server that listens for messages on port 41234.

JavaScript
//udp_server.js
const dgram = require('dgram');

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

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

server.on('listening', () => {
    const address = server.address();
    console.log(`Server listening on ${address.address}:${address.port}`);
});

server.bind(41234);

UDP Client Code

This code sends a message to the UDP server and then closes the socket.

JavaScript
//udp_client.js
const dgram = require('dgram');

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

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

server.on('listening', () => {
    const address = server.address();
    console.log(`Server listening on ${address.address}:${address.port}`);
});

server.bind(41234);

Steps to Run:

Step1: Open your terminal, navigate to the directory containing udp_server.js, and run.

node udp_server.js

Step2: Open another terminal, navigate to the directory containing udp_client.js, and run:

node udp_client.js

Output:

Screenshot-2024-08-25-211116
Server terminal
Screenshot-2024-08-25-211229
Client terminal

Benefits of UDP/Datagram Module

  • Fast Communication: UDP's connectionless design allows for faster data transmission compared to TCP, making it ideal for time-sensitive applications.
  • Broadcasting Capabilities: UDP makes it easy to broadcast messages to multiple clients with minimal resource use.
  • Low Resource Usage: UDP's lightweight protocol requires fewer system resources, making it suitable for high-performance applications.
  • Simple Error Handling: Basic error handling helps quickly identify and manage issues during data transmission.

Summary:

The UDP/Datagram module in Node.js is handy when you need to build fast network applications. It uses UDP, which doesn’t require setting up a connection before sending messages. This makes it ideal for things like live gaming, streaming, or quickly sending messages to many users at once. With this module, you can keep your application quick and efficient without a lot of extra work.


Next Article
Node.js new Agent() Method

A

abhaykjyo2
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • Node.js-UDP/DataGram

Similar Reads

    Node.js UDP/DataGram Complete Reference
    Node.js UDP/DataGram module provides an implementation of UDP datagram sockets. Example: JavaScript // Importing dgram module const dgram = require('dgram'); // Creating and initializing client // and server socket const client = dgram.createSocket("udp4"); const server = dgram.createSocke
    2 min read
    Node.js Utility Module
    The util module in Node.js provides a variety of utility functions that assist with tasks such as debugging, formatting, and inheritance. It includes methods for inspecting objects, formatting strings, and extending classes. Node.js Utility ModuleThe util module offers essential utilities that are n
    4 min read
    Node.js Utility Module
    The util module in Node.js provides a variety of utility functions that assist with tasks such as debugging, formatting, and inheritance. It includes methods for inspecting objects, formatting strings, and extending classes. Node.js Utility ModuleThe util module offers essential utilities that are n
    4 min read
    Node.js dgram.createSocket() Method
    The dgram.createSocket() method is an inbuilt application programming interface within dgram module which is used to create the dgram.socket object. Syntax: const dgram.createSocket(options[, callback]) Parameters: This method takes the following parameter: options: It will use one of the following
    3 min read
    Node.js new Agent() Method
    The Node.js HTTP API is low-level so that it could support the HTTP applications. In order to access and use the HTTP server and client, we need to call them (by ‘require(‘http’)‘). HTTP message headers are represented as JSON Format. The new Agent({}) (Added in v0.3.4) method is an inbuilt applicat
    4 min read
    Node.js socket.address() Method
    The socket.address() method is an inbuilt application programming interface of class Socket within dgram module which is used to get the object which contains the address information for the socket. Syntax: const socket.address() Parameters: This method does not accept any parameter. Return Value: T
    2 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences