Skip to content
This repository has been archived by the owner on Jan 12, 2022. It is now read-only.

Commit

Permalink
Minor code-cleanup and comment a bit.
Browse files Browse the repository at this point in the history
  • Loading branch information
msiebuhr committed May 23, 2012
1 parent 21a71a2 commit e995ed7
Showing 1 changed file with 19 additions and 11 deletions.
30 changes: 19 additions & 11 deletions lib/statsd-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ function StatsDClient(host, options) {
this.options.socket_timeout = this.options.socket_timeout || 1000;

// Set up re-usable socket
this.socket = undefined;
this.socket_used = false;
this._socket = undefined;
this._socket_used = false;
};

/*
Expand Down Expand Up @@ -57,42 +57,50 @@ StatsDClient.prototype.timing = function (name, time) {
this._send(name + ":" + t + "|ms");
};

/*
* PRIVATE METHODS
*/

/*
* Check if the socket has been used in the previous socket_timeout-interval.
* If it has, we leave it open and try again later. If it hasn't, close it.
*/
StatsDClient.prototype._socket_timeout = function () {
// Is it already closed? -- then stop here
if (!this.socket) {
if (!this._socket) {
return;
}

// Has been used? -- reset use-flag and wait some more
if (this.socket_used) {
this.socket_used = false;
if (this._socket_used) {
this._socket_used = false;
setTimeout(this._socket_timeout.bind(this), this.options.socket_timeout);
return;
}

// Not used? -- close the socket
this.socket.close();
this.socket = undefined;
this._socket.close();
this._socket = undefined;
};

/*
* Send data - and have an optional callback.
*/
StatsDClient.prototype._send = function (data) {
// Create socket if it isn't there
if (!this.socket) {
this.socket = dgram.createSocket('udp4');
if (!this._socket) {
this._socket = dgram.createSocket('udp4');
setTimeout(this._socket_timeout.bind(this), this.options.socket_timeout);
}
this.socket_used = true;
this._socket_used = true;

var message = new Buffer(data);

if (this.options.debug) {
console.warn(message.toString());
}

this.socket.send(message, 0, message.length, this.options.port, this.host);
this._socket.send(message, 0, message.length, this.options.port, this.host);
};

module.exports = StatsDClient;

0 comments on commit e995ed7

Please sign in to comment.