周一上班的第一天,老大说要我熟悉一下网络协议和硬件交互(以前常用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和端口。

posted on 2017-10-25 18:35  凌落成迷  阅读(1438)  评论(0编辑  收藏  举报