UDP
Explore the fundamentals of UDP in Node.js by working with the dgram module to create server and client sockets. Understand UDP's connectionless protocol and its advantages for real-time data transfer. Learn to send and receive messages using event-driven methods and compare UDP with TCP in practical scenarios.
We'll cover the following...
UDP
Alongside TCP,
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);The server-side
- We import the
dgrammodule on line 1. - The
createSocketmethod on line 3 creates a UDP socket. Atypemust be passed; we are usingudp4in our case. The socket returned is an object of theEventEmitterclass. This allows us to use theonmethod to handle