Handle Socket-Data depending on CRLF

The Flex2 IRC Application is nearly finished. It is really easy to develop an application using Flex but I still don’t like it. Anyway the Socket is working very well and as I expected it is only binary data. This means you can only read bytes (numbers) from the Socket-Object.

Here is a little snippet which is very usefull for most protocols that are using the CRLF as a termination char. FTP, HTTP, IRC, POP, etc. The sockwrite() function is also very usefull.

[as] import flash.net.Socket;
import flash.util.*;
import flash.events.*;

private var sock: Socket;
private var str: String;
private function connect(): Void
{
sock.connect(host, port);
sock.addEventListener(EventType.CONNECT, onConnect);
sock.addEventListener(ProgressEventType.SOCKET_DATA, onSockRead);
}

private function sockwrite( str: String ): Void
{
sock.writeUTFBytes( str );
send();
}

private function send(): Void
{
sock.writeByte( 13 );
sock.writeByte( 10 );
sock.flush();
}

private function onSockRead(event: ProgressEvent): Void
{
while ( sock.bytesAvailable > 0 )
{
var byte: uint = sock.readUnsignedByte();
var next: uint;

if ( byte == 13 )
{
if ( sock.bytesAvailable >= 1 )
{
next = sock.readUnsignedByte();

if ( next == 10 )
{ // crlf
onSockData( str );
str = ”;
}
else
{
str += String.fromCharCode( byte );
str += String.fromCharCode( next );
}
}
}
else
str += String.fromCharCode( byte );
}
}

private function onSockData( input: String ): Void
{
/* … */
}
[/as]

Related Posts

7 Responses to “Handle Socket-Data depending on CRLF”


  1. 1 Jason Nussbaum

    Have you tried Socket::readUTFBytes( numBytes:uint ):String?
    -> var messageFromServer:String = sock.readUTFBytes( sock.bytesAvailable );

    That’s working well for me…

  2. 2 joa

    FTP and other protocols do not use the UTF-8/UTF-16 encoding.
    And does redUTFBytes stop at a crlf? Because this is what I wrote about.
    Dispatch an event when the next crlf is reached.

  3. 3 Jason Nussbaum

    While it doesn’t stop on a CrLf, you can easily split the returned string, saving you from having to loop through raw bytes creating the string to process…
    As for the encoding, I haven’t had any trouble with writeUTFBytes (nor readUTFBytes), but I’ll keep my eyes open for issues with protocols not expecting/sending UTF8/16.

  4. 4 joa

    You will get into trouble if you use characters like the ü.
    And for the split method: For sure you can do this. But it is circumstantial to make sure your string really began and ended with a crlf.

  1. 1 Franto.com Flash blog » Collected links to ActionScript 3.0 examples
  2. 2 红烧带鱼
  3. 3 DeCabeza.net » Colección de link útiles sobre ActionScript 3 - desarrollo web, tutoriales, video tutoriales, videotutoriales, flash, photoshop, php, mysql, dreamweaver

Leave a Reply






Close
E-mail It