I am trying to communicate using this protocol. It works fine except when the socket has a lot of data to return. Right now I am checking if a packet ends with \r\n to determine if I have received all the packages. Problem is that sometimes a package can end with \r\n as a line break even if it is not the last package, so I can not use that.
I am using a command queue, because I want to wait for a complete response before sending the next command.
The code with unnecessary stuff removed:
class CustomSocket extends Socket
{
private var _response:String;
private var _commandQueue:Array;
public function CustomSocket()
{
super();
this.addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
}
private function socketDataHandler(event:ProgressEvent):void
{
readResponse();
}
private function readResponse():void {
var str:String = this.readUTFBytes(bytesAvailable);
_response += str;
//BUG: I cannot use this check for determining the end of packets, need to find a new one
if (_response.charAt(_response.length - 1) == "\n" && _response.charAt(_response.length - 2) == "\r")
{
//dispatch the result
commandFinished();
}
}
//writes to the socket
private function sendRequest(request:String):void
{
_response = "";
this. writeln(request);
flush();
writeln("\r\n");
flush();
}
private function writeln(str:String):void
{
try
{
this.writeUTFBytes(str);
}
catch (e:IOError)
{
trace(e);
}
}
private function addCommand():void
{
//adds a command to the queue and executes it
}
private function commandFinished():void
{
//remove executed command and check if there is more commands in the queue to execute
}
}
The problem is in the function readResponse. I've googled a lot without finding anything of interest.
Is there a way to know the total amount of bytes/packets a socket will return? Or a way to detect EOF or that a package is the last?