概述
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) { } }
转载于:https://www.cnblogs.com/frost-yen/p/7903997.html
最后
以上就是欣慰冷风为你收集整理的[ActionScript 3.0] UDP通信的全部内容,希望文章能够帮你解决[ActionScript 3.0] UDP通信所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复