Flash / Flex / ActionScript/Network/Socket
Содержание
Close the Socket in Finally branch
package
{
import flash.display.Sprite;
import flash.errors.IOError;
import flash.net.Socket;
public class Main extends Sprite
{
public function Main()
{
try
{
var s:Socket = new Socket();
s.connect("http://www.cmu.edu/", 80);
} catch(error:IOError) {
trace("I/O Error:", error.message);
} catch(error:SecurityError) {
trace("Security Error:", error.message);
} finally {
s.close();
}
}
}
}
Connecting to a Socket Server
package {
import flash.display.Sprite;
import flash.events.*;
import flash.net.Socket;
public class Main extends Sprite {
private var socket:Socket;
public function Main( ) {
socket = new Socket( );
socket.addEventListener( Event.CONNECT, onConnect );
socket.connect( "localhost", 2900 );
}
private function onConnect( event:Event ):void {
trace( "The socket is now connected..." );
}
}
}
Handling a Built-in Exception
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var socket:Socket = new Socket( );
try {
socket.connect("example.ru", userPort);
} catch (e:SecurityError) {
}
}
}
}
Handling Asynchronous Errors: IOErrorEvent
package
{
import flash.display.Sprite;
import flash.net.Socket;
import flash.events.Event;
import flash.events.IOErrorEvent;
public class Main extends Sprite
{
protected var sock:Socket = new Socket();
public function Main()
{
super();
sock.addEventListener(Event.CONNECT, onSocketOpen);
sock.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
sock.connect("www.cmu.edu", 80);
}
protected function onSocketOpen(event:Event):void
{
trace("Connected succesfully!");
sock.close();
}
protected function onIOError(event:IOErrorEvent):void
{
trace(event.text);
//Error #2031: Socket Error. URL: www.cmu.edu
sock.close();
}
}
}
Receiving Data
Socket read methods for various datatypes
package {
import flash.display.Sprite;
import flash.events.ProgressEvent;
import flash.net.Socket;
public class SocketExample extends Sprite {
private var socket:Socket;
public function SocketExample( ) {
socket = new Socket( );
socket.addEventListener( ProgressEvent.SOCKET_DATA, onSocketData );
socket.connect( "localhost", 2900 );
}
private function onSocketData( event:ProgressEvent ):void {
trace( "Socket received " + socket.bytesAvailable + " byte(s) of data:" );
while ( socket.bytesAvailable ) {
var data:int = socket.readByte( );
trace( data );
}
}
}
}
Sending Data
package{
import flash.display.Sprite;
import flash.net.*;
public class Main extends Sprite{
public function Main(){
var socket:Socket = new Socket( );
socket.writeMultiByte("example", "unicode");
socket.writeUTFBytes("USER exampleUsername\n");
socket.writeByte(1);
socket.writeByte(5);
socket.writeByte(4);
socket.writeByte(8);
socket.flush( );
}
}
}