class Socket { private static socketReceiveList : SocketReceive [ ] = [ ] ; private static ip : string ; private static port : number ; private static webSocket : egret . WebSocket ; public static UUID : string ; public static init ( url , userName ) { this . webSocket = new egret . WebSocket ( ) ; this . webSocket . addEventListener ( egret . ProgressEvent . SOCKET_DATA , this . onReceiveData , this ) ; this . webSocket . addEventListener ( egret . Event . CONNECT , this . onConnected , this ) ; this . webSocket . addEventListener ( egret . Event . CLOSE , this . onConnectClose , this ) ; this . webSocket . addEventListener ( egret . IOErrorEvent . IO_ERROR , this . onIOError , this ) ; this . webSocket . connectByUrl ( url + "/" + userName ) ; } public static register ( socketReceive ) { if ( this . socketReceiveList . some ( item => ( socketReceive . module == item . module ) ) ) { throw 'module is exist' ; } this . socketReceiveList . push ( socketReceive ) ; } public static writeOff ( module ) { for ( let i = 0 ; i <= this . socketReceiveList . length ; i ++ ) { let socketReceive = this . socketReceiveList [ i ] ; if ( socketReceive . module == module ) { this . socketReceiveList . splice ( i , 1 ) ; break ; } } } public static send ( data ) { this . webSocket . writeUTF ( this . UUID + JSON . stringify ( data ) ) ; } private static onReceiveData ( e ) { let response = this . webSocket . readUTF ( ) ; console . log ( "onReceiveData:" , response ) ; if ( response . length == 0 ) { return ; } let res = JSON . parse ( response ) ; for ( let socketReceive of this . socketReceiveList ) { if ( socketReceive . module == res . module ) { socketReceive . receive ( res . code , res . data ) ; } } } private static onConnected ( ) { console . log ( 'webSocket' , 'connect success' ) ; } private static onConnectClose ( ) { console . log ( 'webSocket' , 'connect closed' ) ; } private static onIOError ( ) { console . log ( 'webSocket' , 'IO Error' ) ; } }