I am trying to understand your question. If the below explanation deviates from yours, just ignore it.
This is a bit low-level on protocol buffering. There may be third party libraries available to transfer json on as3 as such, you can use them (Eg: http://code.google.com/p/as3corelib etc)
Data you receive at your client end may be chunk-ed or you may get all at once. So in-order to keep track of data size (amount of data you receive), you need to know the size of data server is sending. To do this, we generally code first few bytes (usually 4 bytes) of data with the size of complete data. This might change based on the protocol both client and server have agreed to.
Data = "<4 Bytes >< Rest of the data>"
So once you get the size of data the server is sending, you have to keep an internal buffer to collect the data until it receives the complete data.
I'll tell you how you can do this actionscript. This was taken from
I have added comments for your understanding...
private function onResponse(e:ProgressEvent):void{
trace("Recieved Response");
//InputBuffer is socket buffer
if (inputBuffer.bytesAvailable == 0)
inputBuffer.clear();
//copy all bytes from socket buffer, to internal buffer - this way you avoid working on socket buffer internally
//and have more control on the pulling data your way. Because server keeps on appending data to socket buffer,
//you may lose control
readBytes(inputBuffer, inputBuffer.length, bytesAvailable);
//AS3 is single threaded, we'll create a new event for our data
//processing so that socket buffers its data from server seperately.
dispatchEvent(new Event("DataComplete"));
}
//DataComplete Event
function onCompleteData(event:Event):void {
trace("Complete Data");
//We havent got the requires data size from server
if (requiredSize == -1) {
//Look for first four bytes - that has our data size.
if (inputBuffer.bytesAvailable < 4 ) {
return;
}
var sizeBuffer:ByteArray = new ByteArray();
inputBuffer.readBytes(sizeBuffer,0 , 4);
var ipStream1:CodedInputStream = CodedInputStream.newInstance(sizeBuffer);
requiredSize = ipStream1.readRawLittleEndian32();
}
if (requiredSize == -1) return;
trace( "Req: " + requiredSize + " buffer_length: " + buffer.length + " bytes_Available: " + inputBuffer.bytesAvailable + " bytes_Position: " + inputBuffer.position);
//Now you know the size of data server is sending... just extract that amount of data from socket buffer to internal buffer.
if ((requiredSize - buffer.length) > inputBuffer.bytesAvailable) {
inputBuffer.readBytes(buffer,buffer.length , inputBuffer.bytesAvailable);
return;
} else {
inputBuffer.readBytes(buffer, buffer.length , (requiredSize - buffer.length));
}
trace("Before processing: " + buffer.length);
...Process your data here....
requiredSize = -1;
lastReadByte = -1;
buffer = new ByteArray();
if (inputBuffer.bytesAvailable > 0) {
onCompleteData(null);
}
}