I got confused by a weird problem trying to use ByteArrays to send an object and unsigned int on top of Socket. I am trying to handle the case where I can receive data in multiple packets.
Here is my socket data handler:
protected function handleSocketData(e:ProgressEvent):void{
var s:Socket = e.target as Socket;
trace("pre if " + len + " " + s.bytesAvailable);
if (len == 0 && s.bytesAvailable >= 4) {
len = s.readUnsignedInt();
}
trace(len + " " + s.bytesAvailable);
if (len > 0 && s.bytesAvailable >= len){
var ba:ByteArray = new ByteArray();
s.readBytes(ba, 0, s.bytesAvailable);
ba.inflate();
var o:Object = ba.readObject();
Overlord.updatePlayers(o);
trace(o.player);
len = 0;
}
}
The problem is s.readBytes(ba, 0, len);
I use len (defined in the class scope) to handle the case where I can get multiple packages. Now this seems to work first when I receive data through a socket.
pre if 0 44 - trace I'm getting before the first if statement
38 40 - trace I'm getting after
frank - Everything comes in fine, working!
Now, if I send the data over the socket again:
**first send:**
pre if 0 44
38 40
frank - working, yay!
**things start to fail every send after:**
pre if 0 46
218759168 42
pre if 218759168 84
218759168 84
pre if 218759168 127
218759168 127
Now it seems that readBytes leaves data in the buffer.
The strange part, when I change s.readBytes(ba, 0, len);to s.readBytes(ba, 0, s.bytesAvailable);, everything works:
With s.readBytes (ba, 0, s.bytesAvailable);
**first send**
pre if 0 44
38 40
frank
**everything seems to work after, no old data in the buffer?**
pre if 0 44
38 40
frank
pre if 0 43
37 39
frank
bytesAvailable , .
pre if 2214 2218
2214 2218
RangeError: Error
at flash.utils::ByteArray/readObject()
, , , , socket.bytesAvailable. - ?
. ByteArray , .
public function sendData(socketData:*):void{
if(_connected){
var ba:ByteArray = new ByteArray();
ba.writeObject(socketData);
ba.position = 0;
ba.deflate();
socket.writeUnsignedInt(ba.length);
socket.writeBytes(ba, 0, ba.length);
socket.flush();
} else {
throw new Error("Socket not open");
}
}