I've come up with this, but still have a flaw there:

private function handleTcpData(event:Event):void {
        var len:uint;
        
        if (0 == _socket.bytesAvailable)
                return;
                
        try {
                _socket.readBytes(_ba, _ba.bytesAvailable, 
_socket.bytesAvailable);
                
                // read the length of the UTF string to follow
                while (_ba.bytesAvailable >= 2) {
                        len = _ba.readUnsignedShort();
                
                        // invalid length - reset
                        if (0 == len) {
                                trace('XXX invalid len = ' + len);
                                _ba.position = 0;
                                _ba.length = 0;
                                return;
                        }
                        
                        if (_ba.bytesAvailable >= len) {
                                var str:String = _ba.readUTFBytes(len);
                                updateGUI(str);
                                
                                // copy the remaining bytes
                                // (does it work? can it be improved?)
                                var newBA:ByteArray = new ByteArray();
                                newBA.readBytes(_ba);
                                _ba = newBA;
                        }
                }
        } catch(e:Error) {
                trace('XXX ' + e);
                _ba.position = 0;
                _ba.length = 0;
                return;
        }
}

- when there are too many bytes available, for example 800
and my messages are only 400 bytes long, then it stucks.

Also I wonder, if copying remaining bytes could be
improved (i.e. without allocating a new ByteArray each time)?

Regards
Alex
_______________________________________________
Flashcoders mailing list
Flashcoders@chattyfig.figleaf.com
http://chattyfig.figleaf.com/mailman/listinfo/flashcoders

Reply via email to