Skip to content

Instantly share code, notes, and snippets.

@pward123
Created March 4, 2014 16:45
Show Gist options
  • Save pward123/9350216 to your computer and use it in GitHub Desktop.
Save pward123/9350216 to your computer and use it in GitHub Desktop.
{
getItems: function() {
var future = new Future()
,onComplete = future.resolver()
,sequence = 0
,waitingOnReplies = []
,replies = []
,buffer = ''
,client
;
client = new net.Socket({
type: 'tcp4'
});
client.setEncoding('utf8');
client.setKeepAlive(true, 1000);
client.on('error', function(err) {
throw err;
});
client.on('timeout', function() {
client.destroy();
throw new Meteor.Error(500, 'Socket timed out');
})
client.on('end', function() {
client.end();
onComplete(null, replies); // todo put the received data in here
})
client.on('data', function(dataReceived) {
var msg
,nullIndex
,doc
,sequenceReceived
,sequenceIdx
;
nullIndex = dataReceived.indexOf('\u0000');
while ((dataReceived.length > 0) && (nullIndex > -1)) {
msg = buffer + dataReceived.substring(0,nullIndex);
dataReceived = dataReceived.substring(nullIndex+1);
buffer = '';
doc = new DOMParser().parseFromString(msg);
replies.push(doc);
sequenceReceived = doc.documentElement.getAttribute('seq');
sequenceIdx = waitingOnReplies.indexOf(sequenceReceived);
if (sequenceIdx === -1) {
console.log(JSON.stringify(waitingOnReplies));
throw new Meteor.Error(500, 'received reply for unexpected sequence: ' + sequenceReceived)
} else {
waitingOnReplies.splice(sequenceIdx,1);
if (waitingOnReplies.length === 0) {
console.log('all replies received. closing connection');
client.end();
}
}
nullIndex = dataReceived.indexOf('\u0000');
}
if (dataReceived.length > 0) {
buffer += dataReceived;
}
});
client.connect(port,host,function() {
var dataSent;
sequence++;
dataSent = '<<<<MY REQUEST GOES HERE>>>>\0';
waitingOnReplies.push(sequence.toString());
client.write(dataSent);
});
return future.wait();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment