boganov / merapi

Automatically exported from code.google.com/p/merapi
0 stars 1 forks source link

Reading socket data must respect message boundaries. #6

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
Sometimes the server sends more bytes than one message at once, i.e. the
next message or at least the first bytes of it.
This breaks class Bridge.as.

In Bridge.handleReceiveSocketData(), these lines:

__client.readBytes( __byteBuffer, __byteBuffer.length,
__client.bytesAvailable );

should be something like this:

var readActually : int = Math.min( __totalBytes - __byteBuffer.length,
__client.bytesAvailable );

__client.readBytes( __byteBuffer, __byteBuffer.length, readActually ); 

Assume two messages, one of length 3, one of length 4, e.g. bytes: 3 50 51
52 4 60 61 62 63

When the server sends one chunk of data, say "3 50 51 52 4",
Bridge will read all four bytes (as __client.bytesAvailable == 4).
which is wrong: The next call of handleReceiveSocketData()
will read "60 61 62 63" and therefore will wait for 60 bytes!

What is the expected output? What do you see instead?

Please use labels and text to provide additional information.

Original issue reported on code.google.com by oliver.e...@gmx.de on 19 Aug 2009 at 7:15

GoogleCodeExporter commented 9 years ago
If doing so, it must be ensured that the whole socket buffer is read, even 
without a
new Event from the socket.

So, wrap the whole thing by a while loop:

private function handleReceiveSocketData( event : ProgressEvent ) : void 
{
  while ( __client.bytesAvailable > 0 ) {
  //  The first byte sent by the native side of the bridge is the total
  //  packet size. This value is persisted and reset to -1 when a set 
  //  of messages have been read successfully.
  if ( __totalBytes == -1 )
...

and

...
    dispatchMessage( new MerapiErrorMessage( MerapiErrorMessage.DESERIALIZE_ERROR ) );
    }
  } /* end while */
}

Original comment by oliver.e...@gmx.de on 21 Aug 2009 at 7:03