package com.controls.socket { import flash.events.DatagramSocketDataEvent; import flash.events.Event; import flash.events.EventDispatcher; import flash.net.DatagramSocket; import flash.utils.ByteArray; /** * @author: Frost.Yen * @E-mail: 871979853@qq.com * @create: 2017-11-25 下午2:55:53 * */ public class DatagramSocketManager extends EventDispatcher { private var _datagramSocket:DatagramSocket = new DatagramSocket(); private static var _instance:DatagramSocketManager; public var data:String; public function DatagramSocketManager(s:S) { } public static function getInstance():DatagramSocketManager { if(!_instance){ _instance = new DatagramSocketManager(new S()); } return _instance; } public function send(msg:Object,address:String,port:int):void{ //Create a message in a ByteArray var data:ByteArray = new ByteArray(); if(msg is String){ data.writeUTFBytes( msg as String ); }else{ data.writeUTFBytes( JSON.stringify(msg) ); } //Send a datagram to the target try { _datagramSocket.send( data, 0, 0, address, port); log( "Sent message to " + address + ":" +port); } catch ( error:Error ) { log( error.message ); } } public function bind(port:int,ip:String):void { if( _datagramSocket.bound ) { _datagramSocket.close(); _datagramSocket = new DatagramSocket(); } _datagramSocket.bind(port, ip ); _datagramSocket.addEventListener( DatagramSocketDataEvent.DATA, dataReceived ); _datagramSocket.receive(); log( "Bound to: " + _datagramSocket.localAddress + ":" + _datagramSocket.localPort ); } private function dataReceived( event:DatagramSocketDataEvent ):void { //Read the data from the datagram data = event.data.readUTFBytes( event.data.bytesAvailable ) ; log("Received from " + event.srcAddress + ":" + event.srcPort + "> " + data); this.dispatchEvent(new Event(Event.CHANGE)); } public function log(message:String):void { trace(message); } } } class S{};
用法:
DatagramSocketManager.getInstance().bind(8090,"127.0.0.1"); DatagramSocketManager.getInstance().addEventListener(Event.CHANGE,onGetUDPMsg); private function onGetUDPMsg(e:Event):void{ trace("接收到服务器发送过来的消息",DatagramSocketManager.getInstance().data); try { var data:Object = JSON.parse(DatagramSocketManager.getInstance().data); } catch(error:Error) { } }