Open In App

Node.js UDP/DataGram Complete Reference

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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.createSocket("udp4");
 
// Catching the message event
server.on("message", function (msg) {
 
    // Displaying the client message
    process.stdout.write("UDP String: " + msg + "\n");
 
    // Exiting process
    process.exit();
})
    .bind(1234, () => {
 
        // Adding a multicast address for
        // others to join
        server.addMembership('224.0.0.114');
    });
 
// Client sending message to server
client.send("Hello", 0, 7, 1234, "localhost");


Output:

UDP String: Hello

The Complete List of UDP/Datagram is listed below:

Class: dgram.Socket

Class: dgram.Socket Methods

Description

address() Get the object which contains the address information for the socket.
addMembership() Make the kernel join a multicast group at the particular multicast address.
bind() Bind the particular data gram server to a particular port with some required information.
connect() Connect the particular server to a particular port and address.
dropMembership() Make the kernel leave a multicast group at the particular multicast address.
getSendBufferSize() Get the size of the socket sends the buffer in bytes.
getRecvBufferSize() Get the size of the socket receives buffer in bytes.
setTTL()  Set or clear the IP_TTL socket option which helps to specify how many numbers 
setMulticastTTL() Set or clear the IP_MULTICAST_TTL socket option which helps to specify how many numbers
unref() Allow the process to exit even if the socket is still listening.
setMulticastInterface() Set the default ongoing multicast interface into the socket.
setMulticastLoopback() Set or clear the IP_MULTICAST_LOOP socket
setBroadcast() Set or clear the SO_BROADCAST socket 
setSendBufferSize() Set the size of the socket sends buffer in bytes.
send() Send the message from one socket to another socket.
remoteAddress() The remote address of the server contains the port, address, and family.
ref() Get the reference of the particular socket containing all the information in it.
setRecvBufferSize() Set the size of the socket receives buffer in bytes.
createSocket() Create the dgram.socket object.


Last Updated : 04 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads