So, i've been learning AS3 as some of you may know and i think its high time i wrote up a simple but useful tutorial. I have basically just completed my connection and packet parser class for an engine i've been working on.
Note
The two classes i have released are in the package (folder) Network.
Connection.as
PHP Code:
package Network
{
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.net.Socket;
/**
* ...
* @author Sam Hellawell
*/
public class Connection extends Socket
{
public function Connection(host:String, port:int)
{
super(host, port); //super ftw, creating a new socket
//listen for connection event
addEventListener(Event.CONNECT, onConnect);
//listen for an error, coz we're so cool
addEventListener(IOErrorEvent.IO_ERROR, onError);
}
public function sendData(what:String):void
{
//write the bytes...
this.writeUTFBytes(what);
//now send them!
flush();
}
private function onConnect(e:Event):void
{
//we're connected, so remove the listener
removeEventListener(Event.CONNECT, onConnect);
//listen for close connection event
addEventListener(Event.CLOSE, onClose);
//listen for packets
addEventListener(ProgressEvent.SOCKET_DATA, onResponse);
trace('Connected to the server!');
}
private function onClose(e:Event):void
{
trace('Connection closed. owned.'); //handling?
}
private function onError(e:IOErrorEvent):void
{
trace('Connection Error!'); //maybe add handling?
}
private function onResponse(e:ProgressEvent):void
{
//lets get our data
var str:String = readUTFBytes(bytesAvailable);
//create a new packet instance to parse it
var packet:Packet = new Packet(str);
//kill the packet var
packet = null;
}
}
}
Packet.as
PHP Code:
package Network
{
/**
* ...
* @author Sam Hellawell
*/
public class Packet
{
public function Packet(what:String)
{
trace("got: " + what);
//might wanna parse your packet mate
}
}
}
Usage
PHP Code:
var myConnection:Connection = new Connection("localhost", 1232); //host, port
The classes' comments pretty much explain everything, enjoy!