Skip to content

Instantly share code, notes, and snippets.

@mdobson
Last active January 1, 2016 05:39
Show Gist options
  • Save mdobson/8100270 to your computer and use it in GitHub Desktop.
Save mdobson/8100270 to your computer and use it in GitHub Desktop.
UDP Server Notes in Nodejs
var dgram = require('dgram');
var UDPServer = function() {
};
UDPServer.prototype.createServer = function(msgCallback) {
var sock = dgram.createSocket('udp4');
this.sock = sock;
sock.on('message', function(msg, rinfo){
msgCallback(this, msg, rinfo);
});
};
UDPServer.prototype.close = function() {
this.sock.close();
};
UDPServer.prototype.listen = function(host, port, cb) {
if(arguments.length < 3) {
this.sock.bind(host, port);
} else {
this.sock.bind(host, port, function(){
cb();
});
}
};
var srv = new UDPServer();
srv.createServer(function(sock, message, rinfo){
console.log(message.toString());
console.log(JSON.stringify(rinfo));
sock.send(message, 0, message.length, rinfo.port, rinfo.address, function(err, bytes) {
if(err) {
console.log(arguments);
} else {
console.log("sent");
}
});
});
srv.listen(3000, function() {
console.log("Bound to port 3000");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment