Skip to content

Commit

Permalink
Default to ephemeral sockets
Browse files Browse the repository at this point in the history
The use of a single, shared socket that's never closed prevents node processes
from completing normally.

This change allows an optional shared socket to be passed into the constructor.
If present, node-statsd will use that (and will assume that the provider will
close it when appropriate).  Otherwise, node-statsd will create new sockets for
each connection (the old, less efficient behavior).
  • Loading branch information
mojodna committed Sep 15, 2011
1 parent e67ef94 commit 2584c08
Showing 1 changed file with 28 additions and 10 deletions.
38 changes: 28 additions & 10 deletions lib/statsd.js
@@ -1,11 +1,14 @@
var sys = require('sys')
, socket = require('dgram').createSocket('udp4')
, dgram = require('dgram')
, mersenne = require('mersenne')
, mt = new mersenne.MersenneTwister19937();

Client = function (host, port) {
Client = function (host, port, socket) {
this.host = host;
this.port = port;

// optional shared socket
this.socket = socket;
}

Client.prototype.timing = function (stat, time, sample_rate) {
Expand Down Expand Up @@ -40,6 +43,28 @@ Client.prototype.update_stats = function (stats, delta, sampleRate) {
self.send(data, sampleRate);
}

Client.prototype.send_data = function (buffer) {
var self = this;
var socket;

if (this.socket === undefined) {
socket = dgram.createSocket('udp4');
} else {
socket = this.socket;
}

socket.send(buffer, 0, buffer.length, this.port, this.host, function (err, bytes) {
if (err) {
console.log("Error while sending data:", err.msg);
}

if (self.socket === undefined) {
// close ephemeral sockets while keeping shared ones open
socket.close();
}
});
}

Client.prototype.send = function (data, sample_rate) {
var self = this;
if (!sample_rate) {
Expand All @@ -60,14 +85,7 @@ Client.prototype.send = function (data, sample_rate) {
}
for (stat in sampled_data) {
send_data = stat+":"+sampled_data[stat];
send_data = new Buffer(send_data);
socket.send(send_data, 0, send_data.length, self.port, self.host,
function (err, bytes) {
if (err) {
console.log(err.msg);
}
}
);
this.send_data(new Buffer(send_data));
}
};

Expand Down

0 comments on commit 2584c08

Please sign in to comment.