Browse Source

Add callback to dgramSocket.send()

v0.7.4-release
Ryan Dahl 15 years ago
parent
commit
cbf2a2233e
  1. 28
      lib/dgram.js
  2. 7
      test/simple/test-dgram-pingpong.js

28
lib/dgram.js

@ -146,17 +146,33 @@ Socket.prototype.address = function () {
Socket.prototype.send = function(port, addr, buffer, offset, length) { Socket.prototype.send = function(port, addr, buffer, offset, length) {
var self = this; var self = this;
var lastArg = arguments[arguments.length - 1];
var callback = typeof lastArg === 'function' ? lastArg : null;
if (!isPort(arguments[0])) { if (!isPort(arguments[0])) {
try {
if (!self.fd) { if (!self.fd) {
self.type = 'unix_dgram'; self.type = 'unix_dgram';
self.fd = socket(self.type); self.fd = socket(self.type);
} }
sendto(self.fd, buffer, offset, length, 0, port, addr); var bytes = sendto(self.fd, buffer, offset, length, 0, port, addr);
} catch (e) {
if (callback) callback(e);
return;
}
if (callback) callback(null, bytes);
} else { } else {
dns.lookup(arguments[1], function (err, ip, addressType) { dns.lookup(arguments[1], function (err, ip, addressType) {
// DNS error
if (err) { if (err) {
if (callback) callback(err);
self.emit('error', err); self.emit('error', err);
} else { return;
}
try {
if (!self.fd) { if (!self.fd) {
self.type = addressType == 4 ? 'udp4' : 'udp6'; self.type = addressType == 4 ? 'udp4' : 'udp6';
self.fd = socket(self.type); self.fd = socket(self.type);
@ -165,8 +181,14 @@ Socket.prototype.send = function(port, addr, buffer, offset, length) {
self._startWatcher(); self._startWatcher();
}); });
} }
sendto(self.fd, buffer, offset, length, 0, port, ip); var bytes = sendto(self.fd, buffer, offset, length, 0, port, ip);
} catch (err) {
// socket creation, or sendto error.
if (callback) callback(err);
return;
} }
if (callback) callback(null, bytes);
}); });
} }
}; };

7
test/simple/test-dgram-pingpong.js

@ -4,7 +4,9 @@ var dgram = require("dgram");
var tests_run = 0; var tests_run = 0;
function pingPongTest (port, host) { function pingPongTest (port, host) {
var callbacks = 0;
var N = 500; var N = 500;
var count = 0; var count = 0;
var sent_final_ping = false; var sent_final_ping = false;
@ -17,7 +19,9 @@ function pingPongTest (port, host) {
if (/PING/.exec(msg)) { if (/PING/.exec(msg)) {
var buf = new Buffer(4); var buf = new Buffer(4);
buf.write('PONG'); buf.write('PONG');
server.send(rinfo.port, rinfo.address, buf, 0, buf.length); server.send(rinfo.port, rinfo.address, buf, 0, buf.length, function (err, sent) {
callbacks++;
});
} }
}); });
@ -58,6 +62,7 @@ function pingPongTest (port, host) {
assert.equal(N, count); assert.equal(N, count);
tests_run += 1; tests_run += 1;
server.close(); server.close();
assert.equal(N-1, callbacks);
}); });
client.addListener("error", function (e) { client.addListener("error", function (e) {

Loading…
Cancel
Save