Flash Sokect Newsletter

Source: Internet
Author: User
Tags server port
Package Net
{
Import flash.events.Event;
Import Flash.events.EventDispatcher;
Import flash.events.IOErrorEvent;
Import flash.events.ProgressEvent;
Import flash.events.SecurityErrorEvent;
Import Flash.net.Socket;
Import Flash.utils.ByteArray;
Import Flash.utils.Endian;

Import Org.aswing.JOptionPane;

Import Test. Usercontroltest;

Import UI. Consolepane;




public class Appsocket extends Eventdispatcher
{


protected var Debug:boolean = false;


protected Var callerurl:string;


protected Var socketurl:string;


VARs returned from discovery
public Var sessionid:string;


protected Var heartbeattimeout:int;


protected Var connectionclosingtimeout:int;


protected Var Protocols:array;


Hold over variables from constructor for discover to use
private Var domain:string;


private Var protocol:string;


private Var proxyhost:string;


private Var Proxyport:int;


private Var headers:string;


private var ackregexp:regexp = new RegExp (' (\\d+) \\+ (. *) ');


private var ackid:int = 0;


private var acks:object = {};


Public Function Appsocket ()
{
}


Public Function Initsocket (): void
{
Socket = new socket ();
Init ();
Addevent ();
}


Public Function Setsocket (service:socket): void
{
socket = Service;
Init ();
Addevent ();
}


Private Function init (): void
{
Socket.endian = Endian.big_endian;
socket.objectencoding = 0;


Bean = new Responsebeanparse ();
CacheData = new ByteArray ();
}


Private Function addevent (): void
{
Socket.addeventlistener (Event.connect, onConnect);
Socket.addeventlistener (Event.close, onClose);
Socket.addeventlistener (Progressevent.socket_data, ondata);
Socket.addeventlistener (Ioerrorevent.io_error, onError);
Socket.addeventlistener (Securityerrorevent.security_error, onsecurity);
}


Public function Connect (host:string, port:int): void
{
Config::local
{
Trace (' Connect: ' + host + ': ' + Port ');
}
This.host = host;
This.port = port;
Socket.connect (host, Port);
}


Public function Close (): void
{
Socket.close ();
}


/**
* Send data
*
* @param cmd command code
* @param data
*/
Public Function SendData (req:string): void
{
Config::local
{
Trace ("Send:" + req.tostring ());
}
if (socket.connected)
{
var str:string = json.stringify (req);
Trace (str);
var buffer:bytearray = new ByteArray ();
Buffer.writeutfbytes (req);


Socket.writeshort (buffer.length);

Socket.writebytes (buffer);
Socket.flush ();

CONSOLEPANE.INS.ADDCLIENTMSG (req);
}
}


/**
* Response when connecting to the server
*
* @param E
*/
Private Function OnConnect (e:event): void
{
Config::local
{
Trace ("Socket has been connected!");
}

Usercontroltest.getinstance (). Init ();
This.dispatchevent (e);
var str:string = ' 2[' connection ', {}] ';
NetService.instance.sendData (str);
NetService.instance.sendData ({action: ' Userjoin ', Session: ' Test ', GameID: ' Fishing_haiwang2 ', tableid:100});
}


/**
* Server Active Disconnect Socket response
*
* @param E
*/
Private Function OnClose (e:event): void
{
Config::local
{
Trace ("Socket has been closed!");
}
This.dispatchevent (e);
}


/**
* Receive Server Data response events
* @param E
*/
Private function OnData (e:progressevent): void
{
var socketbytes:bytearray = new ByteArray ();
Socket.readbytes (socketbytes, 0, socket.bytesavailable);
socketbytes.position = 0;

Check (socketbytes); Data processing
}

Public function Check (Dataary:bytearray): void
{
Cachedata.position = Cachedata.length;
Cachedata.writebytes (dataary);
cachedata.position = 0;
Processcachedata ();
}

Public Function Processcachedata (): void
{
if (cachedata.length >= 2)
{
var length:int = Cachedata.readshort ();
if (cachedata.length >= length + 2)
{
cachedata.position = 0;
var d:bytearray = new ByteArray ();
D.writebytes (CacheData, 2, length);
d.position = 0;
ProcessData (d);

cachedata.position = 0;
var l:bytearray = new ByteArray ();
L.writebytes (CacheData, (length + 2));
CacheData = l;
cachedata.position = 0;

Processcachedata ();
}
}
}


Private Function ProcessData (D:bytearray): void
{
var str:string = d.readutfbytes (d.bytesavailable);

try{
var msg:object = json.parse (str);
}catch (e:error) {
Trace (e.message);
Return
}

CONSOLEPANE.INS.ADDSERVERMSG (str);
Trace (' Received Server message: ' +str ');
if (Msg.content.status = = "Error") {
Joptionpane.showmessagedialog ("", Msg.content.error + "\ n" + msg.content.debug);
Return
}
var Command:icommad = actionregister.getaction (msg.event);
if (command) Command.excute (msg);
var Responsebean:abstractresponsebean = Bean.parse (ALLDATA);
if (Responsebean)
//            {
var msgcode:int = Responsebean.getmsgcode ();
var Action:icommad = actionregister.getaction (Msgcode);
if (action)
//                {
Action.excute (Responsebean);
//                }
Else
//                {
Config::local
//                    {
Trace ("Unhandled message:" + Msgcode);
//                    }
//                }
Config::local
//                {
Trace ("handler:" + responsebean.tostring ());
//                }
//            }
Else
//            {
Config::local
//                {
Trace ("unhandled message");
//                }
//            }
}


Private Function OnError (e:event): void
{
Config::local
{
Trace ("Socket IO error?!");
}

This.dispatchevent (e);
}


Private Function Onsecurity (e:event): void
{
Config::local
{
Trace ("Socket security Error!");
}

This.dispatchevent (e);
}


Public function Get IsConnected (): Boolean
{
return _isconnected;
}


Public function set IsConnected (Value:boolean): void
{
_isconnected = value;
}




private Var headstr:string;


private Var Socket:socket;


/**
* Server Address
*/
private Var host:string;


/**
* Server Port
*/
private Var Port:int;


/**
* Socket Connection Successful
*/
private var _isconnected:boolean = false;


private Var Cachedata:bytearray; Cached data
}

}



========================== If you think it's useful to you, please support me, just a little bit, thank you ======================


                     


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.