XML Sockets in Flash - Common Utilizations
(Page 3 of 5 )
Having outlined the methods and event handlers common to the XMLSocket object, let’s discuss how they all work together. Here is some sample code for a connection from Flash to a server with no functionality for sending, receiving, or parsing.
myXML = new XMLSocket;
myXML.onConnect = handleConnect;
myXML.connect("http://www.yourServer.com", 12345);
function handleConnect(connectionStatus){
connectionStatus ? trace("Connected.") : trace("Connection failed.");
}
As you can see, there really isn't that much to initiating a socket connection to your server.
So that you can test your Flash code, here is a very condensed socket server written in Perl. This server has no special functionality built in. It simply echoes anything it receives from any client to all clients connected. Notice that the only real change needed from a standard basic socket server is the setting of the null character as the EOL indicator (in Perl: $/="\0";).
use IO::Socket;
use IO::Select;
$SIG{PIPE}='IGNORE';
$m=new IO::Socket::INET(Listen=>1,LocalPort=>2229);
$O=new IO::Select($m);
$/="\0";
while(@S=$O->can_read){
foreach(@S){
if($_==$m){
$C=$m->accept;$O->add($C);
}else{
my $R=sysread($_, $i, 2048);
if($R==0){
$T=syswrite($_, '', 2048);
if($T==undef){
$O->remove($_);
}
}else{
foreach $C($O->handles){
$T=syswrite($C, $i,2048);
}
}
}
}
}
As was mentioned in the previous section, any language can handle Flash's sockets, as long as it can open ports, and recognize the null character as an EOL character. Socket apps have been written in Perl, PHP, Java, C++, and I'm sure in many other languages.
Since there really isn't any need to explain the above ActionScript code, we will provide an example that uses most of the functionality the object has to offer.
myXML = new XMLSocket;
myXML.onConnect = handleConnect;
myXML.onXML = handleXML;
myXML.onClose = handleDisconnect;
myXML.connect("http://www.yourServer.com", 12345);
function handleConnect(connectionStatus){
connectionStatus ? trace("Connected.") : trace("Connection failed.");
}
function handleXML(xmlObject){
trace("Object recieved:: "+xmlObject);
}
function sendXML(textToSend){
myXML.send(new XML('"+textToSend+""));
}
function handleDisconnect(){
trace("Connection lost.");
}
function closeConnection(){
trace("Closing connection to server.");
myXML.close();
}
That pretty much covers the basic implementation of the methods, and event handlers. But that's only the starting point. Where you take it from here will depend on the solution you're working to implement.
Next: Possibilities >>
More Flash Articles
More By Richard Lyman