当前位置:   article > 正文

as3 udp

as3 udp

   周一上班的第一天,老大说要我熟悉一下网络协议和硬件交互(以前常用Socket所以我认为是要从UDP和串口开始着手),好吧,你是老大你说的算,然后我就开始学习UDP。

  先贴接收的代码:

public class Main extends MovieClip {
        private var txt:TextField=new TextField();
        private var datagramSocket:DatagramSocket=new DatagramSocket();
        public function Main() {
            // constructor code
            
            addChild(txt);
            txt.text="aaaaaaaa";
            bindFunc();
        }
        private function bindFunc():void{
            if(datagramSocket.bound){
                datagramSocket.close();
                datagramSocket=new DatagramSocket();
            }
            datagramSocket.bind(8080,"192.168.1.130");
            datagramSocket.addEventListener(DatagramSocketDataEvent.DATA,onDataEvent);
            datagramSocket.receive();
        }
        private function onDataEvent(e:DatagramSocketDataEvent):void{
            trace("ip"+e.srcAddress);
            trace("port"+e.srcPort);
            //var str=e.data.readUTFBytes(e.data.bytesAvailable);
            var str=e.data.readUTFBytes(e.data.bytesAvailable);
            trace(e.data.readUTFBytes(e.data.bytesAvailable));
            //trace(e.data.readUTFBytes(e.data.objectEncoding));
            trace("msg"+str);
            txt.text=str;
        }
        
    }

然后贴发送的代码:

public class Main extends MovieClip {
        
        private var udpSocket:DatagramSocket=new DatagramSocket();
        private var bytes:ByteArray=new ByteArray();
        private var txt:TextField=new TextField();
        public function Main() {
            // constructor code
            //bytes.writeUTFBytes("1234");
            //bytes.writeUTF("hello");
            bytes.writeUTFBytes("hello");
            udpSocket.send(bytes,0,0,"192.168.1.130",8080);
            bytes.clear();
            stage.addEventListener(MouseEvent.CLICK,onC);
            addChild(txt);
            txt.type=TextFieldType.INPUT;
            txt.border=true;
        }
        private function onC(e:MouseEvent):void{
            //bytes.writeUTF(txt.text);
            bytes.writeUTFBytes(txt.text);
            udpSocket.send(bytes,0,0,"192.168.1.130",7777);
            bytes.clear();
        }
    }

 

  其实后来我琢磨了一下,UDP应该是接收的时候要绑定自己的IP和端口,发送的时候要写对方的IP和端口。

转载于:https://www.cnblogs.com/lingLuoChengMi/p/7731523.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/998850
推荐阅读
相关标签
  

闽ICP备14008679号