@@ -86,14 +86,13 @@ Connection.prototype.connect = function(port, host) {
86
86
Connection . prototype . attachListeners = function ( stream ) {
87
87
var self = this ;
88
88
var reader = new Readable ( ) ;
89
- reader . wrap ( stream ) ;
89
+ reader = reader . wrap ( stream ) ;
90
90
reader . on ( 'readable' , function ( ) {
91
- self . setBuffer ( reader . read ( ) ) ;
92
- var msg = self . parseMessage ( ) ;
91
+ var msg = self . parseMessage ( reader ) ;
93
92
while ( msg ) {
94
93
self . emit ( 'message' , msg ) ;
95
94
self . emit ( msg . name , msg ) ;
96
- msg = self . parseMessage ( ) ;
95
+ msg = self . parseMessage ( reader ) ;
97
96
}
98
97
} ) ;
99
98
reader . on ( 'error' , function ( error ) {
@@ -324,34 +323,39 @@ Connection.prototype.readSslResponse = function() {
324
323
} ;
325
324
} ;
326
325
327
- Connection . prototype . parseMessage = function ( ) {
328
- var remaining = this . buffer . length - ( this . offset ) ;
329
- if ( remaining < 5 ) {
330
- //cannot read id + length without at least 5 bytes
331
- //just abort the read now
332
- this . lastBuffer = this . buffer ;
333
- this . lastOffset = this . offset ;
334
- return false ;
326
+ Connection . prototype . parseMessage = function ( reader ) {
327
+ //I want to get rid of this bit here...
328
+ if ( ! this . header ) {
329
+ //try to read the 5 byte header
330
+ this . header = reader . read ( 5 ) ;
331
+ if ( ! this . header ) {
332
+ return false ;
333
+ }
335
334
}
336
335
337
336
//read message id code
338
- var id = this . buffer [ this . offset ++ ] ;
337
+ var id = this . header [ 0 ] ;
339
338
//read message length
340
- var length = this . parseInt32 ( ) ;
341
-
342
- if ( remaining <= length ) {
343
- this . lastBuffer = this . buffer ;
344
- //rewind the last 5 bytes we read
345
- this . lastOffset = this . offset - 5 ;
346
- return false ;
339
+ var length = this . header . readInt32BE ( 1 , true ) ;
340
+
341
+ var bodyLength = length - 4 ;
342
+ //some packets have an empty body
343
+ if ( bodyLength ) {
344
+ var body = reader . read ( bodyLength ) ;
345
+ if ( ! body ) {
346
+ return false ;
347
+ }
348
+ //blow away header
349
+ this . buffer = body ;
350
+ this . offset = 0 ;
347
351
}
352
+ this . header = false ;
348
353
349
354
var msg = {
350
355
length : length
351
356
} ;
352
357
switch ( id )
353
358
{
354
-
355
359
case 0x52 : //R
356
360
msg . name = 'authenticationOk' ;
357
361
return this . parseR ( msg ) ;
@@ -419,6 +423,7 @@ Connection.prototype.parseMessage = function() {
419
423
case 0x48 : //H
420
424
msg . name = 'copyOutResponse' ;
421
425
return this . parseGH ( msg ) ;
426
+
422
427
case 0x63 : //c
423
428
msg . name = 'copyDone' ;
424
429
return msg ;
0 commit comments