Writing A UDP Server Using Node.js

Previously, I’ve written about using node.js to send a heartbeat to a python server using a UDP datagram.

Of course you may not want to run Python if you using node.js so I thought I’d give you a quick run through on writing a UDP server using node.js.

The earlier heartbeat example sent a small message saying “PyHB” to a server listening on port 43278. This example will listen out for that message and show it on the console to prove it’s working.

The first thing we need to do is to require("dgram") to allow us access to the dgram library.

var dgram = require("dgram");

We now need to create a datagram socket to listen on, as we’re going to listen out for an IP4 datagram we create this of type udp4.

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

Node.js lets us bind to events, and dgram gives us three, message, listening and close.

To listen for an event, we need to use the listening event. As with other JavaScript events, we can pass in a callback function to actually do something when the event is fired. In this case, we’ll just use display the incoming message on the console, along with some details of the server that sent it.

server.on("message", function (msg, rinfo) {
  console.log("server got: " + msg + " from " + rinfo.address + ":" + rinfo.port);
});

It’s also useful to know we’ve actually setup our socket correctly, so we can use the listening event to return a message to console that everything has been setup OK and is working.

server.on("listening", function () {
  var address = server.address();
  console.log("server listening " + address.address + ":" + address.port);
});

Finally we need to actually bind our socket to a port so it can start listening for messages. For this we have to use the bind method.

server.bind(43278);

Putting this all together we have the following code that can listen for UDP datagrams and show them on the console.

var dgram = require("dgram");
var server = dgram.createSocket("udp4");
server.on("message", function (msg, rinfo) {
  console.log("server got: " + msg + " from " + rinfo.address + ":" + rinfo.port);
});
server.on("listening", function () {
  var address = server.address();
  console.log("server listening " + address.address + ":" + address.port);
});
server.bind(43278);

I hope this has been a useful quick introduction to writing a UDP server in node.js.

One thought on “Writing A UDP Server Using Node.js”

Comments are closed.