diff --git a/lib/index.js b/lib/index.js index fbf5a521..1919a207 100644 --- a/lib/index.js +++ b/lib/index.js @@ -42,6 +42,13 @@ Client.prototype.connect = function() { con.on('data', function(data) { console.log('data!'); console.log(data); + var parser = new Parser(data); + con.end(); + var result = parser.parse(); + while(result) { + console.log(result); + result = parser.parse(); + } }); }; @@ -52,14 +59,18 @@ var Parser = function(buffer) { var p = Parser.prototype; -p.parse = function(buffer) { - switch(this.buffer[this.offset]) { +p.parse = function() { + if(this.buffer.length == this.offset) { + return false; + } + var messageID = this.buffer[this.offset]; + switch(messageID) { case UTF8.R: return this.parseR(); case UTF8.S: return this.parseS(); default: - throw new Error("Unsupported message ID"); + throw new Error("Unsupported message ID: " + Buffer([messageID]).toString('utf8')); } }; @@ -67,14 +78,16 @@ p.parseR = function() { var type = this.buffer[this.offset++]; var length = this.parseLength(); if(length == 8) { + this.offset += 4; return { name: 'AuthenticationOk', id: 'R', length: length } - } + }p throw new Error("Unknown AuthenticatinOk message type"); }; + p.parseS = function(buffer) { var type = this.buffer[this.offset++]; var length = this.parseLength(this.buffer); diff --git a/test/parser-tests.js b/test/parser-tests.js index a809a276..631228e0 100644 --- a/test/parser-tests.js +++ b/test/parser-tests.js @@ -37,5 +37,10 @@ test('Parser on single messages', function() { assert.equal(result, 3); assert.equal(parser.offset, 4); }); + + test('parsing empty buffer returns false', function() { + var parser = new Parser(Buffer(0)); + assert.equal(parser.parse(), false); + }); });