Created
July 11, 2013 18:09
-
-
Save skeggse/5977764 to your computer and use it in GitHub Desktop.
Node Streams2 UDPStream Implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var dgram = require('dgram'); | |
var _ = require('underscore'); | |
var thumbs = { | |
twiddle: function() {} | |
}; | |
_.mixin({ | |
options: function(self, options, defaults) { | |
if (options) | |
_.extend(self, _.defaults(_.pick(options, _.keys(defaults)), defaults)); | |
else | |
_.extend(self, defaults); | |
} | |
}); | |
var defaults = { | |
address: '0.0.0.0', | |
type: 'udp4', | |
port: 12345, | |
broadcast: null, | |
multicast: null, | |
multicastTTL: 1 | |
}; | |
var UDPStream = function(options) { | |
if (!(this instanceof UDPStream)) | |
return new UDPStream(options); | |
Duplex.call(this); | |
_.options(this, options, defaults); | |
this._socket = dgram.createSocket(this.type, setup.bind(this)); | |
this._socket.on('message', this.push.bind(this)); | |
}; | |
util.inherits(UDPStream, Duplex); | |
var setup = function() { | |
if (this.multicast) { | |
this._socket.addMembership(this.multicast); | |
this._socket.setMulticastTTL(this.multicastTTL); | |
this.destination = this.multicast; | |
} else { | |
// default to using broadcast if multicast address is not specified. | |
this._socket.setBroadcast(true); | |
// TODO: get the default broadcast address from os.networkInterfaces() (not currently returned) | |
this.destination = this.broadcast || '255.255.255.255'; | |
} | |
}; | |
UDPStream.prototype._read = function(size) { | |
thumbs.twiddle(); | |
}; | |
UDPStream.prototype._write = function(chunk, encoding, callback) { | |
this._socket.send(chunk, 0, chunk.length, this.port, this.destination); | |
}; | |
module.exports = UDPStream; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment