Example UDP client and server nodejs

Server:

 

var PORT = 4444;

var HOST = '127.0.0.1';

var dgram = require('dgram');

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

server.on('listening', function () {

    var address = server.address();

    console.log('UDP Server listening on ' + address.address + ":" + address.port);

});

 

server.on('message', function (message, remote) {

    console.log(remote.address + ':' + remote.port +' - ' + message);

       var msgResponse="OK";

       server.send(msgResponse, 0, msgResponse.length, remote.port, remote.address, function(err, bytes) {

    if (err) throw err;

     console.log('UDP server message sent to ' + remote.address +':'+ remote.port);

});

});

server.bind(PORT, HOST);

 

Client:

 

var PORT = 4444;

var HOST = '127.0.0.1';

 

var dgram = require('dgram');

var message = new Buffer('I am Thor!');

 

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

client.send(message, 0, message.length, PORT, HOST, function(err, bytes) {

    if (err) throw err;

    console.log('UDP client message sent to ' + HOST +':'+ PORT);

   

});

client.on('message', function (message, remote) {

    console.log(remote.address + ':' + remote.port +' - ' + message);

       client.close();

 

});

 

Run server:

 

D:\codewr\ServerUDP>node serverUDP.js

UDP Server listening on 127.0.0.1:4444

127.0.0.1:52208 - I am Thor!

UDP server message sent to 127.0.0.1:52208

 

Run client:

 

D:\codewr\ServerUDP>node clientUDP.js

UDP client message sent to 127.0.0.1:4444

127.0.0.1:4444 - OK