Skip to content

Commit

Permalink
rewritten with drain event, should be ok now
Browse files Browse the repository at this point in the history
  • Loading branch information
bobrik committed Sep 26, 2011
1 parent 47519f5 commit 2097d6f
Showing 1 changed file with 13 additions and 24 deletions.
37 changes: 13 additions & 24 deletions lib/apn.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ var Connection = function (optionArgs) {
, enhanced: true /* enable enhanced format */
, errorCallback: undefined /* Callback when error occurs */
, cacheLength: 5 /* Number of notifications to cache for error purposes */
, writeTimeout: 10 /* Timeout to wait for empty buffer */
};

if (optionArgs) {
Expand All @@ -45,15 +44,23 @@ var Connection = function (optionArgs) {
var readyToConnect = function () {
return (hasKey && hasCert);
}

var startSocket = function () {

var onDrain = function() {
if (offlineCache.length) {
while (self.socket.socket.bufferSize == 0 && offlineCache.length) {
self.writeNotificationToSocket(offlineCache.pop());
}
}
};

var startSocket = function () {
self.socket = tls.connect(options['port'], options['gateway'], socketOptions,
callback = function() {
if(!self.socket.authorized) {
throw self.socket.authorizationError
}

self.scheduleOfflineCacheChecking();
onDrain();
});

self.socket.on('data', function(data) {
Expand All @@ -73,6 +80,8 @@ var Connection = function (optionArgs) {
self.socket.removeAllListeners();
self.socket = undefined;
});

self.socket.on("drain", onDrain);
}

var connect = invoke_after(function() { startSocket(); });
Expand Down Expand Up @@ -103,32 +112,12 @@ var Connection = function (optionArgs) {
} else {
if (self.socket.socket.bufferSize > 0) {
offlineCache.push(data);
self.scheduleOfflineCacheChecking();
} else {
self.socket.write(data);
}
}
};

this.recheckOfflineCache = function() {
console.log("RECHECK");
if (offlineCache.length) {
self.writeNotificationToSocket(offlineCache.pop());
}

self.offlineCacheScheduler = undefined;

if (offlineCache.length) {
self.scheduleOfflineCacheChecking();
}
};

this.scheduleOfflineCacheChecking = function() {
if (!self.offlineCacheScheduler) {
self.offlineCacheScheduler = setTimeout(self.recheckOfflineCache.bind(self), options.writeTimeout);
}
};

this.sendNotification = function (note) {
var token = note.device.token;
var message = JSON.stringify(note);
Expand Down

0 comments on commit 2097d6f

Please sign in to comment.