Here is a quick tutorial on simulating UDP client and server connections using Netcat (NCat). Dgram package is built into all regular NodeJS installations, so you have nothing to setup.

UDP Server

  • Create server.js file with below code.
const dgram = require('dgram');
const server = dgram.createSocket('udp4');

const HOST = '0.0.0.0';
const PORT = 30000;

server.on('error', (err) => {
    console.log(`server error:\n${err.stack}`);
    server.close();
});

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

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

server.bind({
    address: HOST,
    port: PORT,
    exclusive: true
});
  • Start the server by running the above file. Feel free to update IP address and port of the host machine as per your wish.
$ node server.js

UDP Client

  • Create client.js file with below code.
const dgram = require('dgram');

const HOST = '0.0.0.0';
const PORT = 30000;
const message = new Buffer('My KungFu is Good!');
const client = dgram.createSocket('udp4');

client.send(message, 0, message.length, PORT, HOST, function(err, bytes) {
    if (err) throw err;
    console.log('UDP message sent to ' + HOST +':'+ PORT);
    client.close();
});
  • Run the client by running the above file. Feel free to update IP address and port of the host machine as per your wish.
$ node client.js

✅ Tested OS's : RHEL 7+, CentOS 7+, Ubuntu 18.04+, Debian 8+
✅ Tested Gear : Cloud (AWS EC2), On-Prem (Bare Metal)

👉 Any questions? Please comment below.


Leave a comment