Week 10 - Programming UDP Sockets in Node.js
For all things UDP in Node.js, you will need to use the
dgram
library, so read it up well and good.UDP Server
Here is a simple example of a UDP server.
var PORT = 33333;
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);
});
server.bind(PORT, HOST);
Things to Note
- HOST is optional in
server.bind()
. If omitted, it will be listening on0.0.0.0
, which might be what you want in some cases. - The
message
event is fired, when a UDP packet arrives destined for this server. - The
listening
event is fired, when the server has initialized and all ready to receive UDP packets. dgram.createSocket()
can either accept 'udp4' or 'udp6'. The former uses IPv4, the later uses IPv6.
UDP Client
And here is a simple UDP client.
var PORT = 33333;
var HOST = '127.0.0.1';
var dgram = require('dgram');
var message = new Buffer('My KungFu is Good!');
var 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();
});
Things to Note
client.send()
requires a proper Node.js Buffer object, not a plain string or number.- The second parameter 0, of
client.send()
is the offset in the buffer where the UDP packet starts. - The third parameter
message.length
, is the number of bytes we want to send from the offset in the buffer. In our case, the offset is 0, and the length ismessage.length
(16 bytes), which is quite tiny and the whole buffer can be sent in a single UDP packet. This might always not be the case. For large buffers, you will need to iterate over the buffer and send it in smaller chunks of UDP packets. - Exceeding the allowed packet size will not result in any error. The packet will be silently dropped. That's just the nature of UDP.
- The
err
object in the callback function ofclient.send()
is going to be only of the DNS lookup kind. - Make sure the HOST / IP address is in conformance with the IP version you use, else your packets will not reach the destination.
Comments
Post a Comment