a blog for those who code

Sunday 12 April 2015

UDP / Datagram Sockets in NodeJS

In this post we are going to discuss about UDP / Datagram socket in NodeJS. As in one of our previous post we have discussed about Create TCP Server in Nodejs. The difference between TCP and UDP is that TCP requires a dedicated connection between the two end points of the communication whereas UDP (User Datagram Protocol) is a connection-less protocol.

Connection-less protocol means there is no guarantee of a connection between the two end points. Because of the above difference UDP is less reliable and robust than TCP, but UDP is generally faster than TCP. Now NodeJS supports both type of connection, in the previous post we have covered about TCP Server in NodeJS, in this post we will be discussing about UDP Sockets in NodeJS.

Datagram sockets are available through require('dgram')
To  create a UDP socket, we need to use createSocket method. 


To create a UDP socket we need to pass the type (either 'udp4' or 'udp6'). We can even pass a callback function to listen for events.

Example : 

var dgram = require('dgram');
var client = dgram.createSocket("udp4");

process.stdin.on('data', function(value) {

  console.log(value.toString('utf8'));

  client.send(value, 0, value.length, 8124, "www.codingdefined.com", function(err, bytes) 
    {
      if(err)
console.log('Error in Connection : ' + err);
      else
console.log('Connection Successful');
    });
});
Output :

The above example shows a demonstration of a UDP client. In this code we have access data via process.stdin and then sent it via UDP socket. There is one more option of creating socket dgram.createSocket(options[,callback]). The option object should contains a type field of either 'udp4' or 'udp6'. For more information about the same visit https://nodejs.org/api/dgram.html

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment